在mysql中组合2个表

时间:2012-06-06 08:54:37

标签: mysql sql

这是我想要做的事情,但我怀疑是否可能!

我有2个表,一个名为users,另一个名为answers。我需要将结果合并到一个语句中,并按time对表进行排序。棘手的部分是我在两个表上都有time,我需要考虑两个time字段来排序结果。

这是我尝试提出查询的失败:

SELECT * FROM ( SELECT id, username, first_name, last_name, time FROM users
UNION ALL
  SELECT id, answer, pid, uid, time FROM answers ) as AB
ORDER BY `AB.time`

更新

我提出了以下SQL查询:

 SELECT username AS user, '' as page , '' as content , time FROM users 
UNION ALL
  SELECT (SELECT username FROM users WHERE `id`=`uid`) AS user, pid AS page, answer AS content, time FROM answers 
ORDER BY `time` DESC

我正在寻找的但由于某种原因,第二个SELECT查询中的user字段显示为null!知道为什么吗?

2 个答案:

答案 0 :(得分:2)

 SELECT id, username, first_name, last_name, time FROM users
UNION ALL
  SELECT id, answer, pid, uid, time FROM answers 
ORDER BY 'time`

解决方案为每个表提供不同的列名

SELECT id         AS t1_id, 
       username   AS t1_username, 
       first_name AS t1_first_name, 
       last_name  AS t1_last_name, 
       NULL       ast2_id, 
       NULL       AS t2_answer, 
       NULL       AS t2_pid, 
       NULL       AS t2_uid, 
       time 
FROM   users 
UNION ALL 
SELECT NULL   AS t1_id, 
       NULL   AS t1_username, 
       NULL   AS t1_first_name, 
       NULL   AS t1_last_name, 
       id     ast2_id, 
       answer AS t2_answer, 
       pid    AS t2_pid, 
       uid    AS t2_uid, 
       time 
FROM   answers 
ORDER  BY time 

答案 1 :(得分:1)

如果users.id和answers.uid应该是相同的,那么这应该有效:

SELECT u.*, a.* FROM users AS u
    JOIN answers AS a ON a.uid = u.id
    ORDER BY a.time