ORDER BY和LIMIT之后的UNION

时间:2011-06-01 08:00:46

标签: mysql sql sql-order-by union

我的目标是执行两个不同的查询,然后将它们组合起来 我的代码是:

SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0,1 
UNION   
SELECT * FROM some tables WHERE ...

我收到以下错误:

  

#1221 - UNION和ORDER BY的使用不正确

ORDER BY仅适用于第一个查询。我该如何执行此任务?

4 个答案:

答案 0 :(得分:26)

您可以使用括号允许在单个查询中使用ORDER / LIMIT

(SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0, 1)
UNION   
(SELECT * FROM some tables WHERE ...)
ORDER BY 1   /* optional -- applies to the UNIONed result */
LIMIT 0, 100 /* optional -- applies to the UNIONed result */

答案 1 :(得分:10)

SELECT * FROM (SELECT * FROM some tables WHERE ... ORDER BY field1 LIMIT 0,1) x
UNION ALL
SELECT * FROM some tables WHERE ...

请注意使用UNION ALL

  • UNION在执行此操作之前从结果集中删除重复的行,并且数据库命令所有行(因此整个结果集已排序)
  • UNION ALL保留订单和重复项

答案 2 :(得分:4)

将所有内容放在圆括号中:

(SELECT * FROM table1 ORDER BY datetime  )
UNION   
(SELECT * FROM table2 ORDER BY datetime DESC)

答案 3 :(得分:2)

(SELECT user_id AS id FROM tbl_user)
UNION
(SELECT address_id AS id FROM tbl_address)
ORDER BY id ASC LIMIT 10