0

我有一个样本数据

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

并使用查询:

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 

如何获得结果的所有价值是

product(ID, name, image, view) =>  1 | iPhone | iPhone.png | 123
4

3 回答 3

1

假设您的样本数据不正确并且您正在尝试获得PIVOT结果,您可以使用MAXwith CASE

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 
于 2013-06-09T01:46:18.507 回答
0

基于与 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
于 2013-06-09T09:47:25.727 回答
0

你可以像 select table1.column1, table2.column2 from .......... 其余查询一样。

于 2013-06-09T01:43:37.783 回答