0

除了一个连接语句之外,我还试图获取一个子查询,该语句将显示所有客户的名字和姓氏,这些客户有一个名为“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;

我究竟做错了什么?

4

3 回答 3

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”),但它是前进的更好语法。

于 2012-09-05T16:28:37.400 回答
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;
于 2012-09-05T16:37:08.603 回答
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
 ;
于 2012-09-05T17:26:07.607 回答