在1个查询中选择两个表,但在获取' id'从第一个表开始,并在选择第二个表时使用它

时间:2014-08-25 22:41:36

标签: sql select union

SELECT status.*, 
       users.username 
FROM   status, 
       users 
WHERE  status.user_id = users.id 
UNION 
SELECT comments.user_id, 
       comments.commente, 
       comments.date_of_creation, 
       users.username 
FROM   comments, 
       users 
WHERE  comments.status_id = (SELECT status.* 
                            FROM   status 
                            WHERE  id = comments.statu_id) && 
                                  comments.user_id = users.id 
ORDER  BY status.id DESC; 

1 个答案:

答案 0 :(得分:1)

我注意到user_id对所有表都是通用的。你只需要一些连接:

SELECT s.*, 
    c.user_id, 
    c.commente, 
    c.date_of_creation, 
    u.username 
FROM users u 
inner join status s on s.user_id = u.user_id
inner join comments c on c.user_id = u.user_id 
ORDER  BY s.id DESC;