我正在尝试构造一个select语句。表结构如下所示。我基本上希望选择左表中的三个字段以及右侧表的meta_values,它们的meta_key为responsible_service和responsible_officer。这些meta_values可能存在也可能不存在。
我的可怕尝试看起来像这样。
SELECT
`wp_posts`.`ID`,
`wp_posts`.`post_content`,
`wp_posts`.`post_title`
FROM(
`wp_posts`
INNER JOIN `wp_postmeta` ON (`wp_posts`.`ID` = `wp_postmeta`.`post_id`),
(Select `wp_postmeta`.meta_value where`wp_postmeta`.meta_key='responsible_officer') as Responsible Officer),
(Select `wp_postmeta`.meta_value where `wp_postmeta`.meta_key='responsible_service') as Responsible Service ),
结果应如下所示
答案 0 :(得分:1)
这将为每wp_posts
。ID
提供一行或多行,具体取决于找到'responsible_officer'和'responsible_service'的数量。如果未找到,则meta_key和meta_value将为null
SELECT
`wp_posts`.`ID`,
`wp_posts`.`post_content`,
`wp_posts`.`post_title`,
max(case `wp_postmeta`.meta_key
when 'responsible_officer' then `wp_postmeta`.meta_value end) as responsible_officer,
max(case `wp_postmeta`.meta_key
when 'responsible_service' then `wp_postmeta`.meta_value end) as responsible_service
FROM
`wp_posts`
LEFT JOIN `wp_postmeta` ON `wp_posts`.`ID` = `wp_postmeta`.`post_id`
AND `wp_postmeta`.meta_key in ('responsible_officer', 'responsible_service')
group by `wp_posts`.`ID`,
`wp_posts`.`post_content`,
`wp_posts`.`post_title`;
答案 1 :(得分:0)
同时检查:
select postmeta.meta_value, posts.ID, posts.`post_content`,
posts.`post_title` from `wp_posts` posts join `wp_postmeta` postmeta on posts.ID = postmeta.post_id where postmeta.meta_key IN ('responsible_officer', 'responsible_service')
答案 2 :(得分:0)
SELECT
`wp_posts`.`ID`,
`wp_posts`.`post_content`,
`wp_posts`.`post_title`
FROM `wp_posts`
JOIN `wp_postmeta` ON (`wp_posts`.`ID` = `wp_postmeta`.`post_id`)
where `wp_postmeta`.meta_key in ('responsible_officer', 'responsible_service')