由于括号放置,mysql union语句失败了吗?

时间:2015-01-15 16:39:01

标签: php mysql sorting

我已经编写了三个有效的sql语句,我正在尝试使用这样的联合:

(SELECT * FROM articles WHERE date <= '2015-01-15' AND category='News' )
UNION
(SELECT * FROM articles WHERE date <= '2015-01-15' AND subcategory='News')
ORDER BY date DESC LIMIT 5
UNION
SELECT * FROM articles WHERE Month(recurring) = '01' AND category='News' ORDER BY 
recurring DESC LIMIT 5

我要问的基本结构是:两个初始查询通过日期联合和排序。 然后是第三个查询,按单独的列排序,然后联合到前两个。

当我分别对括号内的前两个查询进行排序时,上面的查询似乎工作正常,但是一旦我从括号中取出并将它们排序在一起就失败了。

是按单独的列排序导致它失败?我尝试添加一组额外的括号来封装前两个语句加上排序顺序,但是没有去。 这是错误代码:

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在#UNCE SELECT * FROM文章附近使用正确的语法WHERE Month(recurring)=&#39; 01&#39;和类别=&#39;新闻&#39;在第2行

1 个答案:

答案 0 :(得分:2)

您的查询存在一些问题。 UNION查询只能有一个LIMIT子句和一个ORDER BY子句,并且两者都应用于整个结果。

如果我理解你的逻辑,我会将你的查询重写为:

(
  SELECT * FROM articles
  WHERE date <= '2015-01-15' AND (category='News' OR subcategory='News')
  ORDER BY date DESC
  LIMIT 5
)
UNION
(
  SELECT * FROM articles
  WHERE Month(recurring) = '01' AND category='News'
  ORDER BY recurring DESC
  LIMIT 5
)

如果您的查询更复杂并且您确实希望将前两个查询分开,则这是正确的语法:

SELECT * FROM (
    SELECT * FROM articles WHERE date <= '2015-01-15' AND category='News'
    UNION
    SELECT * FROM articles WHERE date <= '2015-01-15' AND subcategory='News'
    ORDER BY date DESC
    LIMIT 5
) AS s
UNION
(
  SELECT * FROM articles
  WHERE Month(recurring) = '01' AND category='News'
  ORDER BY recurring DESC
  LIMIT 5
)