2014-07-08 62 views
0

我目前遇到了MySQL的麻煩。通過JOIN獲得不同的特徵

我有2個表:

TABLE1 
------ 
id name 
1 John 

TABLE2 
------ 
id TABLE1_id name value 
1 1   Age 42 
2 1   Height 172cm 

我想獲得這樣的約翰所有的特點:

name age height 
John 42 172cm 

這裏是我當前的查詢:

SELECT DISTINCT 

       IF(TABLE2.name = "Age", TABLE2.value, 0) as age, 

       IF(TABLE2.name = "Height", TABLE2.value, 0) as height, 

FROM TABLE1 

       LEFT JOIN TABLE2 ON TABLE2.TABLE1_id = TABLE1.id 

WHERE 

       TABLE1.name = "John" 

的問題是查詢返回2行:一個使用Age,另一個使用Height。

我嘗試了幾種聯接類型(左,右等),試圖刪除「DISTINCT」,但我無法解決這個問題。

你能幫忙嗎? :)

+0

是什麼在表2中的ID列嗎? – Strawberry

+0

該id是主鍵。我不需要它的結果:) –

+0

我的猜測是,在你的例子(不像我的例子)(TABLE1_ID,名稱)始終是唯一的。因此,這將起到主鍵的作用。 – Strawberry

回答

1
SELECT * FROM eav_hell; 
+----+--------+-----------+------------+ 
| id | entity | attribute | value  | 
+----+--------+-----------+------------+ 
| 1 |  1 | date  | 03/04/2009 | 
| 2 |  1 | shift  | 1st  | 
| 3 |  1 | station 1 | Mark  | 
| 4 |  1 | station 2 | John  | 
| 5 |  1 | station 2 | Macy  | 
| 6 |  2 | date  | 04/04/2009 | 
| 7 |  2 | shift  | 2nd  | 
| 8 |  2 | station 1 | John  | 
| 9 |  2 | Station 1 | Drey  | 
| 10 |  2 | Station 2 | Macy  | 
+----+--------+-----------+------------+ 
10 rows in set (0.00 sec) 


SELECT entity 
     , MAX(CASE WHEN attribute = 'date' THEN value END) date 
     , MAX(CASE WHEN attribute = 'shift' THEN value END) shift 
     , GROUP_CONCAT(CASE WHEN attribute = 'station 1' THEN value END) station1 
     , GROUP_CONCAT(CASE WHEN attribute = 'station 2' THEN value END) station2 
    FROM eav_hell 
    GROUP 
    BY entity; 
+--------+------------+-------+-----------+-----------+ 
| entity | date  | shift | station1 | station2 | 
+--------+------------+-------+-----------+-----------+ 
|  1 | 03/04/2009 | 1st | Mark  | John,Macy | 
|  2 | 04/04/2009 | 2nd | Drey,John | Macy  | 
+--------+------------+-------+-----------+-----------+ 
+0

我如何與我的第一張桌子一起加入? –

+0

嘗試加入。 – Strawberry

0

這個怎麼樣。它只是單獨unioning第一個表到第二和結果拼接

SELECT "Name" as `Key` ,t1.Name as `Value` 
FROM Table1 t1 
UNION 
SELECT t2.Name as `Key`, t2.Value 
FROM TABLE2 t2 
INNER JOIN TABLE1 t1 on t2.Table1_ID = t1.ID 
WHERE t1.Name = "John" 

的SQL小提琴是在這裏:http://sqlfiddle.com/#!2/544489/11