我正在尝试获取一个子查询以及一个连接语句,该语句将显示所有客户的FirstName和LastName,这些客户订购的商品名为“Dress Shirt”。然后我必须按升序排列LastName排序的结果,然后按降序报告FirstName。这就是我所拥有的,但它一直给我“没有选择的行”:
SELECT FirstName, LastName
FROM HW2G_CUSTOMER, HW2G_ORDER_ITEM
WHERE Item IN
(SELECT Item
FROM HW2G_ORDER_ITEM
WHERE Item = ‘DressShirt’)
ORDER BY LastName ASC, FirstName DESC;
我做错了什么?
答案 0 :(得分:2)
第一个问题是你在两个表之间进行交叉连接。第二个是IN中的子查询没有返回任何结果。 “Dress Shirt”可能不是一个有效的值。但是,请考虑更像是一个查询:
SELECT distinct FirstName, LastName
FROM HW2G_CUSTOMER c join
HW2G_ORDER_ITEM i
on c.customerID = i.customerID
WHERE i.Item = ‘Dress Shirt’
ORDER BY LastName ASC, FirstName DESC;
这不会解决问题(字符串“Dress Shirt”),但它是向前发展的更好的语法。
答案 1 :(得分:1)
你绝对不想要你现在拥有的东西,因为你正在进行交叉连接。看看这个小提琴:
http://www.sqlfiddle.com/#!3/30abb/5
SELECT FirstName, LastName
FROM HW2G_CUSTOMER WHERE CustomerId IN
(SELECT CustomerId
FROM HW2G_ORDER_ITEM
WHERE Item = 'Dress Shirt')
ORDER BY LastName ASC, FirstName DESC;
答案 2 :(得分:0)
-- maybe a bit cleaner than @aqinas 's solution?
WITH wanted AS (
SELECT DISTINCT CustomerId
FROM HW2G_ORDER_ITEM
WHERE Item = 'Dress Shirt'
)
SELECT FirstName, LastName
FROM HW2G_CUSTOMER cus
JOIN wanted wa ON wa.CustomerId = cus.CustomerId
ORDER BY LastName ASC, FirstName DESC
;