0

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

我有两张桌子,一张叫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

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

4

2 回答 2

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 
于 2012-06-06T08:56:36.920 回答
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
于 2012-06-06T08:57:52.783 回答