将两个MYSQL SELECT语句合并/合并为一个

时间:2014-11-19 00:02:26

标签: mysql

我正在使用单个SELECT语句寻求帮助。使用两个语句的示例:

  

第1期:从现在起40天到现在365天

     

第二名:现在开始40天

等于从现在起40天后抵消的所有365天

选择陈述1:

SELECT id FROM sales
 WHERE (saledate BETWEEN DATE_ADD(NOW(), INTERVAL 40 DAY) AND DATE_ADD(NOW(), INTERVAL 365 DAY))
 ORDER BY saledate;

选择陈述2:

SELECT id FROM sales
 WHERE (saledate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 40 DAY))
 ORDER BY saledate;

2 个答案:

答案 0 :(得分:0)

您是否尝试使用UNION

来获得合并结果
(SELECT id FROM sales 
WHERE (saledate BETWEEN DATE_ADD(NOW(), INTERVAL 40 DAY) 
AND DATE_ADD(NOW(), INTERVAL 365 DAY)) 
ORDER BY saledate)

UNION

(SELECT id FROM sales 
WHERE (saledate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 40 DAY)) 
ORDER BY saledate)

答案 1 :(得分:0)

为什么不使用or

SELECT id
FROM sales
WHERE (saledate BETWEEN DATE_ADD(NOW(), INTERVAL 40 DAY) AND DATE_ADD(NOW(), INTERVAL 365 DAY)) OR
       (saledate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 40 DAY))
ORDER BY saledate;

当然,这可以进一步简化:

SELECT id
FROM sales
WHERE saledate BETWEEN (NOW() AND DATE_ADD(NOW(), INTERVAL 365 DAY)
ORDER BY saledate;

但这似乎很明显,我可能会遗漏一些东西。

编辑:

如果这是一个排序问题,那么union all 不是的方式。工会不保证结果的排序。相反,只需:

SELECT id
FROM sales
WHERE saledate BETWEEN (NOW() AND DATE_ADD(NOW(), INTERVAL 365 DAY)
ORDER BY (saledate >= DATE_ADD(NOW(), INTERVAL 40 DAY) ) DESC,
         saledate;