如果其他表中存在引用,则设置标志

时间:2014-03-07 10:04:01

标签: sqlite

如果表寄存器中有一行指向相应的模块表,我想将列active设置为1。遗憾的是,m.id查询中未显示SELECT EXISTS

SELECT *, active
    FROM module m
    JOIN
    (
        SELECT EXISTS(
            SELECT 1 FROM register r WHERE m.id = r.module_id LIMIT 1
        ) AS aktive
    );

test.db的

CREATE TABLE module (
    id INTEGER PRIMARY KEY,
    tag TEXT
);

INSERT INTO module (tag) VALUES ("Module A");
INSERT INTO module (tag) VALUES ("Module B");

CREATE TABLE register (
    id INTEGER PRIMARY KEY,
    module_id INTEGER NOT NULL
);

INSERT INTO register (module_id) VALUES (2);

SELECT * from module;
SELECT * from register;

1 个答案:

答案 0 :(得分:2)

SELECT *, (SELECT EXISTS(
            SELECT 1 FROM register r WHERE m.id = r.module_id LIMIT 1
        ) ) AS active
    FROM module m;