我正在尝试从多个表中选择数据,但我不确定内部联接是否是正确的方法。我有两个表,一个有 comments.userid
和 comments.comment
,另一个有 votes.userid
,并且都有一个 时间
列。
select comments.comment, voted.time, comments.time
from voted
inner join comments on voted.userid = comments.userid
where voted.userid = '12345'
order by voted.time
但现在我的行在 voted.time
和 comments.time
中具有值,即使它们应该是分开的。有没有办法只返回评论或投票,但通过用户 ID 加入并按总时间排序?
最佳答案
你可以尝试这样的事情。如果将其放入 View 中,则可以在调用 View 时发出 ORDER BY。也可以在 View 调用中执行按用户 ID 的过滤。
select 'V' as type, v.userid, v.time from votes v where v.userid = '1234'
union
select 'C' as type, c.userid, c.time from comments c where c.userid = '1234'
关于mysql - 从多个表中按 ID 和时间分组进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707198/