我有一个带有3个内部选择的SQL选择:
select t1.a, t2.b, t3.c
from (select aa as a from ...) as t1 <-- query 1
(select bb as b from ...) as t2 <-- query 2
(select cc as c from ...) as t3 <-- query 3
where
t1.id = t2.id and t2.id = t3.id
查询1的结果集有5行。 查询2的结果集有5行。 查询3的结果集有2行。
所以我的sql只显示两行,因为查询3有2行,我有一个where codition:t1.id = t2.id和t2.id = t3.id。
但最后我想看到5行,其中查询1或/和2没有任何我想得到的结果或默认值。
如果我删除where条件,那么我会得到许多记录,但这也不正确。
你能告诉我怎样才能解决它?
修改
情况就是这样:
+--------+
| client |
+--------+
|
+------------------+
| client_benchmark |
| |
| + fk_client_id |
| + fk_kpi_id |
| + value |
| + last_update |
+------------------+
|
+------+
| kpi |
+------+
insert into kpi (ID, NAME, ALIAS_NAME...) values (1, 'kpi 1'...);
insert into kpi (ID, NAME, ALIAS_NAME...) values (2, 'kpi 2'...);
insert into kpi (ID, NAME, ALIAS_NAME...) values (3, 'kpi 3'...);
insert into KPI (ID, NAME, ALIAS_NAME...) values (4, 'kpi 4'...);
...
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (1, 1, 1, a1_1...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (2, 1, 2, b1_2...);
...
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (3, 2, 1, a2_1...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (4, 2, 1, b2_2...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (5, 2, 1, c2_3...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (6, 2, 1, d2_4...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (7, 2, 1, e2_5...);
...
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (8, 3, 1, a3_1...);
insert into client_benchmark (ID, CLIENT_ID, KPI_ID, VALUE...) values (9, 3, 2, b3_2...);
...
我想要显示:
client_id | kpi_1.name | kpi_1.value | kpi_2.name | kpi_2.value | kpi_3.name | kpi_3.value
----------+------------+-------------+------------+-------------+------------+------------
1 | 'kpi 1' | a1_1 | 'kpi 2' | b1_2 | <null> | <null>
2 | 'kpi 1' | a2_1 | 'kpi 2' | b2_2 | 'kpi 3' | c2_3
3 | 'kpi 1' | a3_1 | 'kpi 2' | b3_2 | <null> | <null>
我需要一个快速有效的sql,尽可能少的sql join命令,我想为此创建一个视图表。
我使用postgreSQL服务器。
THX。
答案 0 :(得分:1)
您需要LEFT JOIN
:
select
t1.a
,t2.b
,t3.c
from table1 as t1
left join table2 as t2
on t1.id = t2.id
left join table3 as t3
on t2.id = t3.id
除非您的子查询中有复杂的逻辑,否则如果您只是在FROM
中指定表名,它可能会更具可读性。
答案 1 :(得分:0)
JOIN?
select aa.a, bb.b, cc.c
from aa
inner join bb on aa.id = bb.id
inner join cc on cc.id = bb.id
where
t1.id = t2.id and t2.id = t3.id