META TABLE ==
meta_id | post_id | meta_key | meta_value
1 | 101 | quantity | 8
2 | 101 | price | 100
3 | 102 | quantity | 7
4 | 102 | price | 56
5 | 103 | quantity | 12
6 | 103 | price | 256
POST TABLE ==
post_id | name | about
101 | Pencil | Luxurious pencil only for you
102 | Eraser | All your mistakes, gone!
103 | Pen | Unrivaled penmanship, stronger than sword.
如何进行查询以发布ID并获取帖子:名称,关于meta:value,price and quantity in one go?
所以结果将是
101 | Pencil | Luxurious pencil only for you | 8 | 100
102 | Eraser | All your mistakes, gone! | 7 | 56
103 | Pen | Unrivaled penmanship, stronger than sword. | 12 | 256
谢谢
答案 0 :(得分:1)
您必须两次join
meta_table。如果数量或价格在给定post_id的meta_table中没有条目,请使用left join
。
select p.post_id, p.name, p.about, m1.meta_value, m2.meta_value
from post_table p
join meta_table m1 on m1.post_id = p.post_id and m1.meta_key = 'quantity'
join meta_table m2 on m2.post_id = p.post_id and m2.meta_key = 'price'