I have a sample data
product (ID, name)
1 | 'iPhone'
2 | 'iPad'
3 | 'iWatch'
product_meta (ID, product_id, meta_key, meta_value)
1 1 image iPhone.png
2 2 view 123
And using query:
SELECT p.*, m.*
FROM product AS p
LEFT JOIN product_meta AS m ON m.product_id = p.ID
WHERE p.ID = 1
GROUP BY p.ID
How to get all value to result is
product(ID, name, image, view) => 1 | iPhone | iPhone.png | 123
Assuming your sample data is incorrect and you're trying to PIVOT
your results, you can use MAX
with CASE
for this:
select p.id,
p.name,
max(case when pm.meta_key = 'image' then pm.meta_value end) image,
max(case when pm.meta_key = 'view' then pm.meta_value end) view
from product AS p
left join product_meta AS pm ON pm.product_id = p.ID
where p.ID = 1
group by p.ID
您可以像从其余查询中选择table1.column1,table2.column2一样。
Based on the same assumption as sgeddes:
SELECT p.id, p.name, mimage.meta_value, mview.meta_value
FROM product AS p
LEFT JOIN product_meta AS mimage
ON mimage.product_id = p.id AND mimage.meta_key = 'image'
LEFT JOIN product_meta AS mview
ON mview.product_id = p.id AND mview.meta_key = 'view'
WHERE p.id = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.