我有一个Wordpress MySQL数据库,我需要创建一个使用SQL的自定义查询。我试图返回当前事件(post),其中“date_start”值小于当前日期,并且“date_end”值大于或等于当前日期。我知道有一个数据记录应该返回但是当我尝试在“date_start”和“date_end”上搜索时没有返回任何内容
这是我以前的旧SQL语句:
select ID, post_name, meta_id, meta_key, meta_value from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id and ((meta_key='date_end' and meta_value >= CURDATE() + interval 1 day) and (meta_key='date_start' and meta_value < CURDATE())) where post_type='programs' order by meta_value
新的SQL语句:
SELECT
ID,
post_name,
(SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_start') AS 'date_start',
(SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_end') AS 'date_end'
FROM wp_posts
WHERE
post_type = 'programs'
AND ((CURDATE() >= (SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_start'))
AND (CURDATE() <= (SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_end')))
ORDER BY `wp_posts`.`ID` ASC
返回的日期是:
ID post_name date_start date_end
1221 culture-analytics 20160307 20160610
2446 culture-analytics-tutorials 20160308 20160311
我也尝试过内连接的date_start和date_end部分在WHERE子句中。
重要提示:wp_postmeta是多对一模式,而'date_start'和'date_end'是单独的记录,但都指向相同的PostID
似乎是什么问题。
答案 0 :(得分:0)
meta_key上有两个冲突的约束。您的查询要求meta_key同时等于“date_start”和“date_end”。
也许尝试这样的事情:
SELECT
ID,
post_name,
meta_id,
(SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_start') AS 'date_start',
(SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_end') AS 'date_end'
FROM wp_posts
WHERE
post_type = 'programs'
AND (SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_start') < CURDATE()
AND (SELECT meta_value FROM wp_postmeta WHERE wp_postmeta.post_id = ID AND meta_key = 'date_end') >= (CURDATE() + INTERVAL 1 DAY)
ORDER BY 4
我无法访问Wordpress数据库,所以我没有运行它,但它可能有用......
答案 1 :(得分:0)
@obe在他的回答中发现了原始查询的核心问题;但我会用额外的连接而不是四个子查询来解决它:
SELECT ID, post_name, meta_id
, beginMeta.meta_key As beginKey, endMeta.meta_key AS endKey
, beginMeta.meta_value AS beginDate
, endMeta.meta_value AS endDate
FROM wp_posts
INNER JOIN wp_postmeta AS endMeta
ON wp_posts.ID = endMeta.post_id
AND endMeta.meta_key='date_end'
AND endMeta.meta_value >= CURDATE() + interval 1 day
INNER JOIN wp_postmeta AS beginMeta
ON wp_posts.ID = beginMeta .post_id
AND beginMeta.meta_key='date_start'
AND beginMeta.meta_value < CURDATE()
WHERE post_type='programs'
ORDER BY beginDate, endDate
;
编辑:这假定(post_id,meta_key)组合在wp_postmeta中是唯一的。