在联合查询中指定要订购的日期

时间:2015-07-24 14:07:05

标签: mysql

我正在做两个不同表的联合,并按日期列进行排序。联盟不应该将两个日期列设为一个吗?它给了我错误:#1052 - order子句中的'date'列是不明确的

我在这里遗漏了什么吗?这是查询:

SELECT comments.*, postid, prayers.date AS date, prayers.type AS type
       FROM comments 
       LEFT JOIN prayers USING (postid) 
       WHERE comments.username = 'hoodleehoo'
       AND comments.new = 1
       AND comments.first = 1
       AND (comments.type = 'prayer' or comments.type = 'answer')
       AND prayers.privacy != 'hidden'
       UNION
       SELECT comments.*, postid, posts.date AS date, comments.type AS type
       FROM comments
       LEFT JOIN posts USING (postid)
       WHERE comments.username = 'hoodleehoo'
       AND comments.new = 1
       AND comments.first = 1
       AND (comments.type = 'post' or comments.type = 'shared')
       ORDER BY date 

更新:

我猜你不能用“约会”。那一定是保守的话。我将日期更改为“date2”,并且工作正常。我敢肯定,我不是唯一会遇到这种情况的人!

3 个答案:

答案 0 :(得分:1)

要使您的查询正常工作,现在最后一行应为ORDER BY posts.date。而你的问题我认为你实际上是在尝试这样做

SELECT * FROM ( SELECT comments.*, postid, prayers.date AS DATE2, prayers.type AS type
               FROM comments 
               LEFT JOIN prayers USING (postid) 
               WHERE comments.username = 'hoodleehoo'
               AND comments.new = 1
               AND comments.first = 1
               AND comments.type = 'prayer'
               AND prayers.privacy != 'hidden'
               UNION
               SELECT comments.*, postid, posts.date AS DATE2, comments.type AS type
               FROM comments
               LEFT JOIN posts USING (postid)
               WHERE comments.username = 'hoodleehoo'
               AND comments.new = 1
               AND comments.first = 1
               AND comments.type != 'prayer')
               ORDER BY DATE2

答案 1 :(得分:0)

您必须使用日期列

指定tablename
file2

答案 2 :(得分:0)

“模糊”消息传递是一个别名问题。 至于订购工会的结果。这里回答:How to order by with union

检查Mark Robinson的回答。我认为它会满足您的需求。