我的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
但是查询必须如上所述返回结果。
答案 0 :(得分:1)
您希望IN
而不是=
进行子选择。 IN
检查成员资格,=
从子查询中提取值(第一个,最后一个,特定于实现),或者当有多个结果时会抛出错误。
select *
from people
where people.pid IN
(
select p_g_bridge.pid
from p_g_bridge
where p_g_bridge.gid IN
(
select groups.gid
from groups
where groups.name = 'users'
)
);
答案 1 :(得分:0)
试试这个并告诉我结果是什么
select people.pid, people.name
where
people.pid=p_g_bridge.pid
and
groups.pid=p_g_bridge.gid
and
groups.name = 'users'