我在尝试执行查询时遇到了一些问题。我有两个表,一个是元素信息表,另一个是与第一个表中的元素相关的记录表。我的想法是在同一行中获取元素信息以及多个记录信息。
可以这样解释结构:
table [ id, name ]
[1, '1'], [2, '2']
table2 [ id, type, value ]
[1, 1, '2009-12-02']
[1, 2, '2010-01-03']
[1, 4, '2010-01-03']
[2, 1, '2010-01-02']
[2, 2, '2010-01-02']
[2, 2, '2010-01-03']
[2, 3, '2010-01-07']
[2, 4, '2010-01-07']
这是我想要实现的目标:
result [id, name, Column1, Column2, Column3, Column4]
[1, '1', '2009-12-02', '2010-01-03', , '2010-01-03']
[2, '2', '2010-01-02', '2010-01-02', '2010-01-07', '2010-01-07']
以下查询获得了正确的结果,但我觉得它非常低效,需要为每个列迭代table2。是否有可能使用子查询并重用它?
SELECT
a.id,
a.name,
(select min(value) from table2 t where t.id = subquery.id and t.type = 1 group by t.type) as Column1,
(select min(value) from table2 t where t.id = subquery.id and t.type = 2 group by t.type) as Column2,
(select min(value) from table2 t where t.id = subquery.id and t.type = 3 group by t.type) as Column3,
(select min(value) from table2 t where t.id = subquery.id and t.type = 4 group by t.type) as Column4
FROM
(SELECT distinct id
FROM table2 t
WHERE (t.type in (1, 2, 3, 4))
AND t.value between '2010-01-01' and '2010-01-07') as subquery
LEFT JOIN table a ON a.id = subquery.id