1

我有两个这样的表:

Occupied                          Subject
+----------+-----------+          +----+---------+
| idClass  | idSubject |          | id |  Name   |
+----------+-----------+          +----+---------+
|        1 |         1 |          |  1 | German  |
|        1 |         2 |          |  2 | English |
|        2 |         3 |          |  3 | Math    |
+----------+-----------+          +----+---------+    

现在我想从一个特殊班级占用的所有科目中获取idName。我试过这个 SQL 语句:

SELECT S._id ,
       S.Name
FROM Subject S
WHERE S._id = ( SELECT O.idSubject
                FROM Occupied O
                WHERE O.idClass = '1' -- '1' is variable and represents the special class
              ) 

但我只从数据库中得到这个结果:

+----+---------+
| id |  Name   |
+----+---------+
|  2 | English |
+----+---------+

所以我输掉了德国队。我的错误在哪里?

4

3 回答 3

3

我认为您可以使用INNER JOIN查询

SELECT S._id ,
       S.Name 
FROM Subject S 
INNER JOIN Occupied O ON O.idSubject = S.id
WHERE O.idClass='1';

正如查尔斯所说,这可能比根据数据库供应商和 sql 分布使用子查询更快

于 2013-06-13T22:48:32.437 回答
1

变化等于IN

SELECT S._id ,
       S.Name
FROM Subject S
WHERE S._id IN ( SELECT O.idSubject
                 FROM Occupied O
                 WHERE O.idClass = '1'
               )
于 2013-06-13T22:46:30.463 回答
0
SELECT S._id, S.Name
FROM Subject S
WHERE EXISTS (
   (SELECT 1
    FROM  FROM Occupied O
    WHERE O.idSubject = S._id
    AND O.idClass= 1 -- probably an integer
    ) ;

问题是WHERE S._id= (...)需要一个标量子查询,它应该只产生一个结果值。你不想要那个;你想要所有满足子查询的行,所以你应该使用 EXISTS() 或 IN() (这是劣质的 NULL 处理)mysql的隐式转换(我认为是OP的DBMS平台)使灾难完成。(在原始查询中,字符串文字与整数列进行比较)

于 2013-06-13T23:07:43.943 回答