我需要检索与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兼容
感谢所有回复的人!
答案 0 :(得分: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 ...)
答案 1 :(得分: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
答案 2 :(得分: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)
通常最好避免使用子查询,因为数据库优化器无法“看到内部”。