我想知道某个ID是否已打开某些功能。但功能在其他表中。
表1:
DECODE
表2:
SAFETY
表3
DECODE
答案 0 :(得分:1)
您可以尝试将JOIN
与条件聚合函数一起使用
create table Table1(
userID int,
Name varchar(50)
);
insert into Table1 values (1,'aaa');
insert into Table1 values (2,'bbb');
insert into Table1 values (3,'ccc');
create table Table2(
functionID int,
userID int
);
insert into Table2 values (1,1);
insert into Table2 values (2,1);
insert into Table2 values (2,2);
insert into Table2 values (3,2);
insert into Table2 values (1,3);
insert into Table2 values (3,3);
查询1 :
SELECT t1.userID,
t1.Name,
IFNULL(MAX(CASE WHEN t2.functionID = 1 then 'true' end),'false') function1Enabled,
IFNULL(MAX(CASE WHEN t2.functionID = 2 then 'true' end),'false') function2Enabled,
IFNULL(MAX(CASE WHEN t2.functionID = 3 then 'true' end),'false') function3Enabled
FROM
Table1 T1
LEFT JOIN Table2 t2 ON t2.userID = T1.userID
GROUP BY t1.userID,
t1.Name
Results :
| userID | Name | function1Enabled | function2Enabled | function3Enabled |
|--------|------|------------------|------------------|------------------|
| 1 | aaa | true | true | false |
| 2 | bbb | false | true | true |
| 3 | ccc | true | false | true |
答案 1 :(得分:0)
SELECT t1.userID, t1.Name
, CASE WHEN COUNT(CASE WHEN t2.functionID = 1 THEN 1 ELSE NULL END) > 0 THEN 'True' ELSE 'False' END AS function1Enabled
, CASE WHEN COUNT(CASE WHEN t2.functionID = 2 THEN 1 ELSE NULL END) > 0 THEN 'True' ELSE 'False' END AS function2Enabled
.... and so on
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.userID = t2.userID
GROUP BY t1.userID, t1.Name
;
注意:
ELSE NULL
;表示ELSE
中没有CASE
IF()
而不是CASE
来缩短此时间,但是CASE对于其他RDBMS更具可移植性。LEFT JOIN
将确保您获得所有table1记录,即使它们没有在table2中映射的功能也是如此。