我必须将 wp_posts 与 wp_postsmeta 连接两次才能获取行。首先是 post_type=product
,然后是 post_type=attachment
。
wp_posts:
╔════╦════════════╦═════════════════════════════════════════════════════╗
║ ID ║ post_type ║ guid ║
╠════╬════════════╬═════════════════════════════════════════════════════╣
║ 48 ║ product ║ http://example.com/xyz ║
╚════╩════════════╩═════════════════════════════════════════════════════╝
wp_postsmeta
╔═════════╦═════════╦═══════════════╦═══════════╗
║ meta_id ║ post_id ║ meta_key ║ meta_value║
╠═════════╬═════════╬═══════════════╬═══════════╣
║ 200 ║ 48 ║ _price ║ 100 ║
╚═════════╩═════════╩═══════════════╩═══════════╝
查询:
接下来,我还想加入 wp_posts
和 wp_postsmeta
再次使用 post_type = attachment
和 meta_key =_thumbnail
╔════╦════════════╦═════════════════════════════════════════════════════╗
║ ID ║ post_type ║ guid ║
╠════╬════════════╬═════════════════════════════════════════════════════╣
║ 150║ attachment ║ http://example.com/xyz.png ║
╚════╩════════════╩═════════════════════════════════════════════════════╝
wp_postsmeta:
╔═════════╦═════════╦═══════════════╦═══════════╗
║ meta_id ║ post_id ║ meta_key ║ meta_value║
╠═════════╬═════════╬═══════════════╬═══════════╣
║ 200 ║ 48 ║ _thumbnail ║ 150 ║
╚═════════╩═════════╩═══════════════╩═══════════╝
然后我使用结果的 meta_value 并再次将其与 wp_posts 连接(主键 wp_posts.id = wp_postsmeta.meta_value),这样我就可以从中获得产品的特色图片。
下面是我的完整查询
SELECT p1.ID, p1.guid, p3.guid
FROM wp_posts p1
JOIN wp_postmeta p2
ON p1.ID = p2.post_id AND
p2.meta_key = '_price' AND
p1.post_type = 'product' AND
p1.post_status = 'publish'
JOIN wp_posts p3
ON p3.ID = p2.post_id AND
p2.meta_key = '_thumbnail_id'
JOIN wp_postmeta p4
ON p4.post_id = p3.ID AND
p3.post_type = 'attachment';
上面的查询返回空结果(它不应该是空的,而是返回如下表)
╔════╦════════════╦═════════════════════════╦════════════════════════════╗
║ ID ║ post_type ║ guid ║ guid ║
╠════╬════════════╬═════════════════════════╬════════════════════════════╣
║ 48 ║ product ║ http://example.com/xyz ║ http://example.com/xyz.png ║
╚════╩════════════╩═════════════════════════╩════════════════════════════╝
最佳答案
试试这个查询
SELECT posts.post_title,posts.ID, posts.post_name, (SELECT guid from wp_posts AS thumbnailpost INNER JOIN `wp_postmeta` ON (`wp_postmeta`.meta_value = thumbnailpost.ID) where `wp_postmeta`.meta_key='_thumbnail_id' AND `wp_postmeta`.post_id = 2856) AS thumbnail FROM `wp_posts` AS posts where posts.post_type = 'product' and posts.post_status='publish' group by posts.ID limit 100
已更新
你想要这样吗?
SELECT p1.ID, p1.guid,
(select p.guid from wp_posts as p where p2.meta_value=p.ID and post_type='attachment') img
FROM wp_posts p1
JOIN wp_postmeta p2
ON p1.ID = p2.post_id AND
p1.post_type = 'product' AND
p1.post_status = 'publish' AND
p2.meta_key = '_thumbnail_id'
JOIN wp_posts p3
ON p3.ID = p2.post_id
关于mysql - 两次连接两个表,每次选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48296521/