【发布时间】:2016-04-23 08:07:35
【问题描述】:
我有以下代码
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;
客户表有以下内容:
customerid | customername | customersaddress
此查询返回以下结果:
customerid | customername | customersaddress | customerid | newspapername | enddate| publishedby
我真正想要的是
customerid | customername | customersaddress | newspapername | magazinename | enddate| publishedby
此处,如果存在杂志名称,则报纸名称字段应为空白,反之亦然。此外,不应存在来自联合操作的 customerid 重复字段,而在我的结果中,报纸名称和杂志名称的值都放在报纸名称标题下。
我该怎么做?
【问题讨论】:
-
您希望 customerid 在结果中出现两次?还是那是一个错字?
-
Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI
JOIN语法-92 SQL 标准(20 多年前),不鼓励使用它