1

我需要检索与 6 或 7 号玩家居住在同一街道和城镇的所有玩家的玩家编号、姓名、街道和城镇;

我不确定如何编写 SQL 查询,我想我需要在 WHERE 子句中有一个子查询,但不知道该怎么做。

这是我想出的,但目前我无法测试它

SELECT playerNo, name, street, town
FROM Players
WHERE street IN ( SELECT street, playerNo
                  FROM Players
                  WHERE playerNo IN (6,7));
AND town IN (SELECT town, playerNo
             FROM Players
             WHERE playerNo IN (6,7));

应该兼容Oracle 10g

感谢所有回复的人!

4

3 回答 3

4

您没有说明您的 DBMS,所以这是 ANSI SQL 解决方案(适用于 Oracle、PostgreSQL、DB2、Teradata、MySQL 以及可能还有很多其他解决方案):

SELECT playerNo, name, street, town
FROM Players
WHERE (street, town) IN (SELECT street, town
                         FROM Players
                         WHERE playerNo IN (6,7));

IN关于运营商的旁注:

您的表达式town IN (SELECT town, playerNO ...无效,因为子选择必须与运算符左侧的列数完全相同IN。在你的情况下,你必须写town IN (SELECT town FROM ...)

于 2012-05-17T17:03:07.017 回答
2

这样的事情应该可以解决问题:

select t.playerNumber, t.name, t.street, t.town
from tablename t
inner join (select street, town from tablename where playerNumber in (6,7)) aux on aux.street = t.street and aux.town = t.town
于 2012-05-17T16:51:53.903 回答
2
SELECT p1.playerNo, p1.name, p1.street, p1.town
FROM Players AS p1
INNER JOIN Players AS p2 ON p2.street = p1.street AND p2.town = p1.town
WHERE p2.playerNo IN (6,7)

通常最好避免子查询,因为数据库优化器无法“看到括号内部”。

于 2012-05-17T17:05:17.543 回答