[英]How to mix SQL data with OR condition
我有一个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'"
我的查询有效,但结果首先是reutnr car
,其次是motorbike
。
我想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
[...]
带有“ month”但格式日期为2017-12-31的示例
演示: http : //rextester.com/MBRS91171
使用IN vs或or简化查询
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
和'post-date'顺序正确
目前尚不清楚您要做什么。 但是,如果要先按car
的邮政类型进行订购,则可以按如下方式按顺序使用CASE
表达式:
...
ORDER BY CASE WHEN post_type = 'car' THEN 0 ELSE 1 END, 'post-date'
这个怎么样
ORDER BY post_date asc,post_type asc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.