我有三个要在MySQL中查询的表,如下所示:
表注释
id | note
-------------------
1 | note 1
2 | note 2
表格索引
id | name
-----------
1 | height
2 | weight
3 | other
表格详细信息
note_id | indices_id | value
-------------------------------------
1 | 1 | 50
1 | 2 | 60
1 | 3 | 20
2 | 1 | 40
2 | 2 | 10
2 | 3 | 50
我需要查询结果如下:
indices.name | note_id = 1 | note_id = 2
------------------------------------------------
height | 50 | 40
weight | 60 | 10
other | 20 | 50
我尝试了以下查询:
SELECT i.name,
(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n,indices i,detail d
WHERE n.id = d.note_id AND i.id = d.indices_id
GROUP BY i.name
但是列Col3
的结果是null
任何帮助,不胜感激!非常感谢!
答案 0 :(得分:3)
您需要使用聚合函数,以免在Col2
和Col3
上获得随机行数据。 MAX
将起作用,因为如果NULL
不匹配,它将忽略note_id
值。另外,您应该使用显式JOIN
语法:
SELECT i.name,
MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n
JOIN detail d ON n.id = d.note_id
JOIN indices i ON i.id = d.indices_id
GROUP BY i.name
输出:
name Col2 Col3
height 50 40
other 20 50
weight 60 10
答案 1 :(得分:0)
这是尼克回答的一种变体。 JOIN
至nodes
是多余的:
SELECT i.name,
MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM detail d JOIN
indices i
ON i.id = d.indices_id
GROUP BY i.name