我正在为数据库管理系统中的考试学习,无论是否合法,我不确定。
在一个俱乐部的数据库中,要求我返回姓名,电子邮件和金额(按年支付)。
数据库如下:
Table Membership
(
id serial PRIMARY KEY,
email text NOT NULL,
... --unnecessary
)
Table Organisation
(
id int REFERENCES Membership(id) PRIMARY KEY,
"name" varchar Not NULL
... -- unnecessary
)
Table SinglePerson
(
id int REFERENCES Membership(id) PRIMARY KEY,
"name" varchar NOT NULL
)
查询如下:
SELECT
Name, Email, Amount
FROM
(SELECT
E.Name, M.Email, 20 AS Amount
FROM
SinglePerson AS E
JOIN
Membership As M ON M.Id = E.Id),
(SELECT
O.Name, M.Email, 150 AS Amount
FROM
Organisation AS O
JOIN
Membership AS M ON M.Id = O.Id);
可以查询吗?
有更好的方法吗?
非常感谢您!
答案 0 :(得分:0)
没有关于子查询的法律-只是语法错误。但是FROM
子句中应该有禁止使用逗号的法律。学习使用正确的,明确的,标准 JOIN
语法。
尽管我会以不同的方式编写查询,但您似乎希望使用UNION ALL
类型的查询:
SELECT sp.Name, M.Email, 20 AS Amount
FROM SinglePerson sp JOIN
Membership M
ON M.Id = sp.Id
UNION ALL
SELECT O.Name, M.Email, 150 AS Amount
FROM Organisation O JOIN
Membership M
ON M.Id = O.Id;
答案 1 :(得分:0)
我会做的:
select
m.name,
m.email,
case when s.id is not null then 20
when o.id is not null then 150
else null
end as amount
from membership m
left join singleperson s on s.id = m.id
left join organisation o on o.id = m.id