我有如下的sql:
PRAGMA foreign_keys = 1;
CREATE TABLE people ( pid INTEGER PRIMARY KEY, name TEXT );
CREATE TABLE groups ( gid INTEGER PRIMARY KEY, name TEXT );
CREATE TABLE p_g_bridge (
pid INTEGER NOT NULL REFERENCES people,
gid INTEGER NOT NULL REFERENCES groups,
PRIMARY KEY ( pid, gid )
);
-- people
INSERT INTO people VALUES ( 1, 'Alice' );
INSERT INTO people VALUES ( 2, 'Bob' );
INSERT INTO people VALUES ( 3, 'Charlie' );
-- groups
INSERT INTO groups VALUES ( 1, 'users' );
INSERT INTO groups VALUES ( 2, 'admin' );
INSERT INTO groups VALUES ( 3, 'web' );
INSERT INTO groups VALUES ( 4, 'db' );
INSERT INTO groups VALUES ( 5, 'nobody' );
-- everyone in users
INSERT INTO p_g_bridge VALUES ( 1, 1 );
INSERT INTO p_g_bridge VALUES ( 2, 1 );
INSERT INTO p_g_bridge VALUES ( 3, 1 );
-- Alice and Bob into admin
INSERT INTO p_g_bridge VALUES ( 1, 2 );
INSERT INTO p_g_bridge VALUES ( 2, 2 );
-- Charlie into web
INSERT INTO p_g_bridge VALUES ( 3, 3 );
-- Alice and Charlie into db
INSERT INTO p_g_bridge VALUES ( 1, 4 );
INSERT INTO p_g_bridge VALUES ( 3, 4 );
下面是表格:
select * from groups;
gid name
---------- ----------
1 users
2 admin
3 web
4 db
5 nobody
sqlite> select * from people;
select * from people;
pid name
---------- ----------
1 Alice
2 Bob
3 Charlie
sqlite> select * from p_g_bridge;
select * from p_g_bridge;
pid gid
---------- ----------
1 1
2 1
3 1
1 2
2 2
3 3
1 4
3 4
我希望查询所有都是“用户”的人,即)结果必须如下:
pid name
---------- ----------
1 Alice
2 Bob
3 Charlie
我写一个这样的查询:
sqlite> select * from people where people.pid = (select p_g_bridge.pid from p_g_bridge where p_g_bridge .gid = (select groups.gid from groups where groups.name = 'users'));
IT 给出的结果如下:
pid name
---------- ----------
1 Alice
但是查询必须返回如上所述的结果。