此刻我有多个要收集为1的查询,只有日期范围在变化,它们是相同的:
查询1:
SELECT COUNT(simp_posts.ID)
FROM simp_posts
INNER JOIN simp_postmeta
ON ( simp_posts.ID = simp_postmeta.post_id )
WHERE ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value = '0' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-08-01 23:33:51' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-08-01 23:33:51' AND simp_posts.post_status = 'wc-pending-cancel'))
查询2:
SELECT COUNT(simp_posts.ID)
FROM simp_posts
INNER JOIN simp_postmeta
ON ( simp_posts.ID = simp_postmeta.post_id )
WHERE ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value = '0' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-09-01 23:33:51' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-09-01 23:33:51' AND simp_posts.post_status = 'wc-pending-cancel'))
查询3:
SELECT COUNT(simp_posts.ID)
FROM simp_posts
INNER JOIN simp_postmeta
ON ( simp_posts.ID = simp_postmeta.post_id )
WHERE ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value = '0' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-10-01 23:33:51' AND simp_posts.post_status = 'wc-active'))
OR ( ( simp_postmeta.meta_key = '_schedule_end' AND simp_postmeta.meta_value > '2018-10-01 23:33:51' AND simp_posts.post_status = 'wc-pending-cancel'))
我希望将这些查询合并为一个,并使其结果为3行,每个计数的结果都为1。 例如我会得到: 182 183 194
谢谢您的帮助
答案 0 :(得分:2)
在where
中具有通用条件,并有条件地汇总日期范围。
请注意@Tim在评论中提到的内容。如果计数必须互斥,请在meta_value
表达式中包含一个case
范围。
SELECT COUNT(CASE WHEN simp_postmeta.meta_value > '2018-08-01 23:33:51'
THEN simp_posts.ID END)
,COUNT(CASE WHEN simp_postmeta.meta_value > '2018-09-01 23:33:51'
THEN simp_posts.ID END)
,COUNT(CASE WHEN simp_postmeta.meta_value > '2018-10-01 23:33:51'
THEN simp_posts.ID END)
FROM simp_posts
INNER JOIN simp_postmeta ON simp_posts.ID = simp_postmeta.post_id
WHERE simp_postmeta.meta_key = '_schedule_end'
AND simp_posts.post_status IN ('wc-active','wc-pending-cancel')
答案 1 :(得分:2)
在MySQL中,您可以通过将SUM()
与布尔值结合使用来简化答案。
您的逻辑很复杂。我认为它可以简化为:
SELECT SUM((pm.meta_value = '0' AND p.post_status = 'wc-active') or pm.meta_value > '2018-09-01 23:33:51'),
SUM((pm.meta_value = '0' AND p.post_status = 'wc-active') or pm.meta_value > '2018-10-01 23:33:51'),
SUM((pm.meta_value = '0' AND p.post_status = 'wc-active') or pm.meta_value > '2018-10-01 23:33:51')
FROM simp_posts p INNER JOIN
simp_postmeta pm
ON p.ID = pm.post_id
WHERE pm.meta_key = '_schedule_end' AND
p.post_status IN ('wc-active', 'wc-pending-cancel')