我目前遇到了MySQL问题。
我有两张桌子:
TABLE1
------
id name
1 John
TABLE2
------
id TABLE1_id name value
1 1 Age 42
2 1 Height 172cm
我想得到John的所有特征:
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。
我尝试了几种JOIN类型(LEFT,RIGHT等),尝试删除" DISTINCT"但是我无法解决这个问题。
你能帮忙吗? :)答案 0 :(得分: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 |
+--------+------------+-------+-----------+-----------+
答案 1 :(得分:0)
这个怎么样?它只是将第一个表分别与第二个表联合起来并将结果加在一起
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