我试图在sql查询中显示同一个表中的两个值。该表包含2个具有这些值的键。
目前,我做了这个
SELECT p.post_title, t.name, pm.meta_value AS address, pm.meta_value AS id
FROM `wp_posts` p
LEFT JOIN wp_term_relationships trr ON p.ID = trr.object_id
LEFT JOIN wp_term_taxonomy tax ON trr.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN wp_terms t ON tax.term_taxonomy_id = t.term_id
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
p.post_type = 'network-type' AND t.slug = 'atm' AND
pm.meta_key IN ('network_address', 'network_branch_atm_id')
但是这显示了
| post_title | name | address | id |
---------------------------------------------
| Post name | bla | 12 | 12 |
| Post name | bla | address 1 | address 1 |
postmeta
表格的值如下
| meta_id | post_id | meta_key | meta_value |
----------------------------------------------------------
| 1212 | 323 | network_address | address 1 |
| 1212 | 323 | network_branch_atm_id | 12 |
我尝试使用CASE
但遇到了错误(用户不允许执行)。
我应该改变什么才能获得
| post_title | name | address | id |
---------------------------------------------
| Post name | bla | address 1 | 12 |
答案 0 :(得分:1)
汇总帖子标题名称,然后转出地址和ID。您遇到的困难(以及我在wm_postmeta
表中找到的)是将信息存储为键和值。它可能需要一些按摩来按照您希望的方式从Wordpress架构中提取数据。
SELECT
p.post_title,
t.name,
MAX(CASE WHEN pm.meta_key = 'network_address' THEN pm.meta_value END) AS address,
MAX(CASE WHEN pm.meta_key = 'network_branch_atm_id' THEN pm.meta_value END) AS id
FROM wp_posts p
LEFT JOIN wp_term_relationships trr
ON p.ID = trr.object_id
LEFT JOIN wp_term_taxonomy tax
ON trr.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN wp_terms t
ON tax.term_taxonomy_id = t.term_id
LEFT JOIN wp_postmeta pm
ON p.ID = pm.post_id
WHERE
p.post_type = 'network-type' AND
t.slug = 'atm' AND
pm.meta_key IN ('network_address', 'network_branch_atm_id')
GROUP BY
p.post_title,
t.name;