SQLite将单个列连接到另一个表中的多个列并选择

时间:2014-07-23 13:28:37

标签: sqlite

我有两个(简化的)表格:

TriggerSensor

id INTEGER
active INTEGER

TriggerLogic

programId INTEGER
ts1 INTEGER
ts2 INTEGER
ts3 INTEGER
ts4 INTEGER

ts1到ts4列包含来自TriggerSensor表的ID。

因此,通过添加TriggerLogic行,我创建了具有不同传感器设置的程序。

是否可以制作

SELECT programId 
FROM TriggerLogic 
WHERE [all triggers are active]?

这样的东西
SELECT programId 
FROM TriggerLogic l 
INNER JOIN TriggerSensor s ON l.ts1 = s.id 
                           AND l.ts2 = s.id 
                           AND l.ts3 = s.id 
                           AND l.ts4 = s.id
WHERE s.active = 1

但是结果只返回所有四个s.active=1的行?

上面的SELECT不会返回任何行。

1 个答案:

答案 0 :(得分:1)

您需要加入TriggerSensor表4次

SELECT programId 
FROM TriggerLogic l 
INNER JOIN TriggerSensor s1 ON l.ts1 = s1.id AND s1.active = 1
INNER JOIN TriggerSensor s2 ON l.ts2 = s2.id AND s2.active = 1
INNER JOIN TriggerSensor s3 ON l.ts3 = s3.id AND s3.active = 1
INNER JOIN TriggerSensor s4 ON l.ts4 = s4.id AND s4.active = 1