如何将SQL数据与OR条件混合使用

时间:2017-09-18 13:18:58

标签: mysql sql

我有一个SQL查询在1月1日到12月31日之间返回2 post_type:

$url = current date (2017 for example)

SELECT * 
FROM `posts` 
WHERE `post_date` 
BETWEEN '".$url."-01-01' 
AND '".$url."-12-31' 
AND post_status = 'publish' 
AND post_type = 'car' 
OR `post_date` 
BETWEEN '".$url."-01-01' 
AND '".$url."-12-31' 
AND post_status = 'publish' 
AND post_type = 'motorbike' 
ORDER BY 'post-date'"

我的查询有效,但结果是car第一个motorbike。{/ p>

我想首先按post_date而不是post_type混合数据。

有什么想法吗?

编辑:

目前的结果:

Car | January
Car | February
Car | April
[...]
Car | July
Car | August
Motorbike | January
Motorbike | March
Motorbike | May
Motorbike | June
[...]  

我想要的是什么:

Car | January
Motorbike | January
Car | February
Motorbike | March
Car | April
Motorbike | May
Motorbike | June
Motorbike | July
Car | August
[...]

'月'的示例,但格式日期为2017-12-31

3 个答案:

答案 0 :(得分:2)

DEMO:http://rextester.com/MBRS91171

使用IN vs或

简化查询
SELECT * 
FROM posts 
WHERE `post_date` 
BETWEEN '2017-01-01' 
  AND '2017-12-31' 
  AND post_status = 'publish' 
  AND post_type in ('car', 'motorbike')
ORDER BY post_date desc;  

或者只是确保order by语法正确。

SELECT * 
FROM `posts` 
WHERE `post_date` 
BETWEEN '".$url."-01-01' 
AND '".$url."-12-31' 
AND post_status = 'publish' 
AND post_type = 'car' 
OR `post_date` 
BETWEEN '".$url."-01-01' 
AND '".$url."-12-31' 
AND post_status = 'publish' 
AND post_type = 'motorbike' 
ORDER BY `post_date`

确保post_date按post_date vs' post-date'

的顺序排列正确

答案 1 :(得分:0)

目前尚不清楚你要做什么。但是,如果您想先按car的帖子类型进行排序,那么您可以按顺序使用CASE表达式:

...
ORDER BY CASE WHEN post_type = 'car' THEN 0 ELSE 1 END, 'post-date'

答案 2 :(得分:0)

这个怎么样

ORDER BY post_date asc,post_type asc