mysql - 从多个表中按 ID 和时间分组进行选择

标签 mysql sql join inner-join

我正在尝试从多个表中选择数据,但我不确定内部联接是否是正确的方法。我有两个表,一个有 comments.useridcomments.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.timecomments.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/

相关文章:

php - mysql 匹配...通过引用字符串变量

SQL: DISTINCT 不适用于游标

mysql - sql查询选择每个用户的最新条目

php - 函数不更新 Mysql 表

php - MySQL 查询获取 post_id 和特征图片 URL

mysql - 一对一加入MySQL

mysql - 在 Snow Leopard 上安装 mysql gem 时出现问题:未初始化的常量 MysqlCompat::MysqlRes

mysql - linq mysql : select multiple column and send the to view

mysql - 仅使用 mysql 和 php 删除旧日志

mysql - 从一个记录中选择两个登录