我正在尝试运行查询来更新WordPress wp_postmeta表中自定义字段的值。数据如下所示:
meta_id post_id meta_key meta_value
------- ------- ------- ----------
1 1 start_date 2011-12-30
2 1 start_time 21:00
3 363 start_date 2011-12-29
4 363 start_time 21:00
5 363 _start_timestamp 2011-12-29 21:00
我想查询添加meta_key
值为_start_timestamp
的记录,该记录结合了给定post_id的start_date
和start_time
值,但是仅在尚未设置_start_timestamp
的情况下。
在进入INSERT查询之前,我试图获得一个可以显示我想要的东西的SELECT查询。我设法创建一个SELECT查询,返回已定义_start_timestamp
的帖子ID,但无法弄清楚如何获取没有定义的帖子ID。
这就是我所拥有的:
SELECT
a.post_id,
CONCAT(a.meta_value, ' ', b.meta_value),
c.meta_value
FROM
wp_postmeta a
INNER JOIN wp_postmeta b ON a.post_id=b.post_id
INNER JOIN wp_postmeta c ON a.post_id=c.post_id
WHERE
a.meta_key = 'start_date'
AND b.meta_key = 'start_time'
AND c.meta_key='_start_eventtimestamp'
返回
post_id CONCAT(a.meta_value, ' ', b.meta_value) meta_value
363 2011-12-29 21:00 2011-12-29 21:00
如果指定_start_timestamp
的{{1}}列中不存在meta_key
,我该如何指定获取结果?在这种情况下,它应该只返回post_id
1。
答案 0 :(得分:2)
尝试:
SELECT
a.post_id,
CONCAT(a.meta_value, ' ', b.meta_value),
c.meta_value
FROM
wp_postmeta a
INNER JOIN wp_postmeta b ON a.post_id=b.post_id
LEFT JOIN wp_postmeta c ON a.post_id=c.post_id AND
c.meta_key='_start_eventtimestamp'
WHERE
a.meta_key = 'start_date'
AND b.meta_key = 'start_time'
AND c.post_id is null
编辑:另一种方法:
SELECT post_id,
'_start_timestamp' as meta_key,
concat(max(case meta_key when 'start_date' then meta_value end), ' ',
max(case meta_key when 'start_time' then meta_value end)
) as meta_value
from wp_postmeta
group by post_id
having max(case meta_key when 'start_date' then meta_value end) is not null and
max(case meta_key when 'start_time' then meta_value end) is not null and
max(case meta_key when '_start_timestamp' then meta_value end) is null