我有以下代码
SELECT *
FROM customer
INNER JOIN
(SELECT
customerid, newspapername, enddate, n.publishedby
FROM
newspapersubscription ns, newspaper n
WHERE
publishedby IN (SELECT publishedby
FROM newspaper
WHERE ns.newspapername = n.NewspaperName)
UNION
SELECT
customerid, Magazinename, enddate, m.publishedby
FROM
magazinesubscription ms, magazine m
WHERE
publishedby IN (SELECT publishedby
FROM magazine
WHERE ms.Magazinename = m.MagazineName)) ON customer.customerid = customerid
ORDER BY
customer.customerid;
customer表具有以下内容:
customerid | customername | customersaddress
此查询返回以下结果:
customerid | customername | customersaddress | customerid | newspapername | enddate| publishedby
我真正想要的是
customerid | customername | customersaddress | newspapername | magazinename | enddate| publishedby
此处,如果存在magazinename,则newspapername字段应为空白,反之亦然。此外,不应出现来自联合操作的customerid的重复字段,而在我的结果中,newspapername和magazinename的值都放在newspapername标题下。
我该怎么做?
答案 0 :(得分:3)
由于您使用'*'查询表,因此您将始终获得两个表中的所有列。要省略此列,您必须手动命名要查询的所有列。要满足您的其他需求,您只需在联合查询中的每个子句中插入一个虚拟列。下面的示例应该可以满足您的需求 -
SELECT customer.customerid, customer.customername, customer.customeraddress, newspapername, magazinename, enddate, publishedby
FROM customer
INNER JOIN
(select customerid, newspapername, null Magazinename, enddate, n.publishedby
from newspapersubscription ns, newspaper n
where publishedby in(select publishedby
from newspaper
where ns.newspapername = n.NewspaperName)
UNION
select customerid, null newspapername, Magazinename, enddate, m.publishedby
from magazinesubscription ms, magazine m
where publishedby in(select publishedby
from magazine
where ms.Magazinename = m.MagazineName))
on customer.customerid = customerid
ORDER BY customer.customerid;
答案 1 :(得分:2)
要获得所需的投影,请构建正确形状的子查询,并使用UNION来获取结果集。 UNION ALL比UNION更好,因为它避免了一种排序:你知道你会得到一个独特的集,因为你正在加入两个不同的表。
select * from (
select customer.*
, n.newspapername
, null as magazinename
, ns.enddate
, n.publishedby
from customer
join newspapersubscription ns
on ns.customerid = customer.customerid
join newspaper n
on n.newspapername = ns.newspapername
union all
select customer.*
, null as newspapername
, m.magazinename
, ms.enddate
, m.publishedby
from customer
join magazinesubscription ms
on ms.customerid = customer.customerid
join magazine m
on m.magazinename = ms.magazinename
)
order by customerid, newspapername nulls last, magazinename ;
以下是我的玩具数据集的输出(缺少publishedby
列:
CUSTOMERID CUSTOMERNAME NEWSPAPERNAME MAGAZINENAME ENDDATE
---------- -------------------- ---------------------- ---------------------- ---------
10 DAISY-HEAD MAISIE THE DAILY BUGLE 30-SEP-17
30 FOX-IN-SOCKS THE DAILY BUGLE 30-SEP-17
30 FOX-IN-SOCKS THE WHOVILLE TIMES 30-SEP-16
30 FOX-IN-SOCKS GREEN NEWS 31-DEC-17
30 FOX-IN-SOCKS TWEETLE BEETLE MONTHLY 31-DEC-16
40 THE LORAX GREEN NEWS 31-DEC-18
6 rows selected.
SQL>