使用ORDER的Mysql查询UNION不起作用

时间:2016-02-24 10:30:31

标签: mysql sql union union-all

我的sql查询存在问题。

此代码适用于有一天发布的节目文章。

示例:

BLOG ONE: day of pubblication every 16th of mounth
BLOG TWO: day of pubblication every 2nd of mounth
BLOG THREE: day of pubblication every 23th of mounth

所以今天24日我必须看到博客的出版日24,25,26,27,28,1,2,3,4,5 .................

问题是合并两个查询

( DAY FROM TODAY TO 31th) + (DAY FROM 1st TO YESTERDAY)

这是第一个问题

$queryallblog = mysql_query("
(
  SELECT * 
  FROM day,blog 
  WHERE day.autore = blog.titolo && day.titolo >= DAY(CURRENT_DATE())
  ORDER BY day.titolo
)") or die(" Error: (" . mysql_errno() . ") " . mysql_error()); 

这是第二个:

$queryallblog = mysql_query("
(
  SELECT * 
  FROM day,blog 
  WHERE day.autore = blog.titolo && day.titolo < DAY(CURRENT_DATE())
  ORDER BY day.titolo
)") or die(" Error: (" . mysql_errno() . ") " . mysql_error()); 

使用UNION STATEMENT全局订单不正确

2 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您的问题不是关于UNION查询,而是关于正确排序结果。我会使用这样的查询:

SELECT
  *
FROM
  day inner join blog on day.autore = blog.titolo
ORDER BY
  case when day.titolo >= DAY(CURRENT_DATE()) then 1 else 2 end,
  day.titolo
  • 我使用内部联接而不是where语法
  • 当day.titolo为&gt; =当前日期时将返回1的情况,否则为2。首先是当天之后返回的行,然后是当天之前的行
  • 然后按天排序行.titolo
  • 您可能需要添加其他过滤器,例如

您可以使用UNION ALL查询获得类似的结果,但您必须添加一个额外的列:

SELECT 1 as t, *
FROM day inner join blog on day.autore = blog.titolo
WHERE day.titolo >= DAY(CURRENT_DATE())
UNION ALL
SELECT 2 as t, *
FROM day inner join blog on day.autore = blog.titolo
WHERE day.titolo < DAY(CURRENT_DATE())
ORDER BY t, day.titolo

但是我不会推荐它,至少在这种情况下不会这样。

答案 1 :(得分:0)

(SELECT * 

FROM day,blog 
WHERE day.autore = blog.titolo && day.titolo >= DAY(CURRENT_DATE())
ORDER BY day.titolo) 
UNION ALL
(SELECT * 

FROM day,blog 
WHERE day.autore = blog.titolo && day.titolo < DAY(CURRENT_DATE())
ORDER BY day.titolo)