如何选择两个表?

时间:2012-02-15 23:03:59

标签: mysql sql

经过相当多的时间尝试和酝酿一些研究后,我终于投降并请求大家帮忙。这就是我的MySQL表格:

表1:

Parent_ID | ID | Name | Quality |Price
1         | 001|Apple | good    |1.50
1         | 002|Apple | medium  |1.20
1         | 003|Apple | poor    |0.99
2         | 004|Car   | good    |5000.00
2         | 005|Car   | poor    |200.00

表2:

Parent_ID | Var_Name | Value
1         | color    |  red
1         | size     |  big
1         | rating   |  3 Star
2         | color    |  blue
2         | size     |  medium
2         | rating   |  ok

好的。太好了。我现在需要的是一个查询,它给了我这个:

Parent_ID | ID  | Name  | Quality |   Price | color | size   | rating
1         | 001 | Apple | good    |    1.50 | red   | big    | 3Star
1         | 002 | Apple | medium  |    1.20 | red   | big    | 3Star
1         | 003 | Apple | poor    |    0.99 | red   | big    | 3Star
2         | 004 | Car   | good    | 5000.00 | blue  | medium | ok
2         | 005 | Car   | poor    |  200.00 | blue  | medium | ok

4 个答案:

答案 0 :(得分:5)

只需加入table2三次过滤JOIN子句中的var_name。

SELECT t.parent_id, 
       t.id, 
       t.name, 
       t.quality, 
       t.price, 
       c.VALUE AS color, 
       s.VALUE AS size, 
       r.VALUE AS rating 
FROM   table1 t 
       LEFT JOIN table2 c 
         ON t.parent_id = c.parent_id 
            AND c.var_name = 'color' 
       LEFT JOIN table2 s 
         ON t.parent_id = s.parent_id 
            AND s.var_name = 'size' 
       LEFT JOIN table2 r 
         ON t.parent_id = r.parent_id 
            AND r.var_name = 'rating' 

答案 1 :(得分:1)

Select T1.Parent_ID, T1.ID, T1.Name, T1.Quality, T1.Price,
    (select value from Table2 T2 where T2.Parent_ID = T1.Parent_ID and Var_Name = 'color') as color,
    (select value from Table2 T2 where T2.Parent_ID = T1.Parent_ID and Var_Name = 'size') as size, 
    (select value from Table2 T2 where T2.Parent_ID = T1.Parent_ID and Var_Name = 'rating') as rating
FROM Table1 T1

答案 2 :(得分:0)

还有一种方法可以做到这一点。它只使用一个连接,但您必须使用聚合函数。

SELECT table1.*, 
max(if(table2.var_name='color',table2.value, NULL)) as color,
max(if(table2.var_name='size',table2.value, NULL)) as size,
max(if(table2.var_name='rating',table2.value, NULL)) as rating,
FROM table1 join table2 
WHERE table1.ID = table2.ID
GROUP BY table.*

答案 3 :(得分:-1)

我所需要的只是一个简单的联接我相信......

SELECT *
FROM Table1 t1
JOIN Table2 t2
  ON t1.Parent_Id = t2.Parent_Id