【问题标题】:How can i return 2 rows in a where select?如何在 where 选择中返回 2 行?
【发布时间】:2013-06-21 04:15:54
【问题描述】:

这是问题所在...我有这些表:

crs
title|semester
c++  |a
java |b
sql  |a

crsstu
regnum|title
11131 |java
11131 |c++
11132 |java
11132 |sql
11133 |c++
11133 |sql

我想做的是从 crsstu 和表格中选择一个注册号(regnum),我想看看他还没有注册哪些课程。 示例:如果我选择 regnum 11131 那么它必须返回 sql,或者使用 11132 它返回 c++。

我已经走到这一步了:

select a.title 
from crs as a,crsstu as b
where b.registrationnumber != 11133 
and a.title != (select title 
                from crsstu 
                where registrationnumber = 11133)

但它显示了一个 1242 错误(子查询返回超过 1 行)。我知道我已经接近答案,但我不知道该怎么做。任何答案都会有帮助。谢谢你提前

【问题讨论】:

    标签: mysql sql sql-server select where


    【解决方案1】:

    只需将!= 更改为NOT IN。 IN 和 NOT IN 允许对一组项目进行比较。

    select a.title 
    from crs as a,crsstu as b
    where b.registrationnumber != 11133 
    and a.title NOT IN (select title 
                    from crsstu 
                    where registrationnumber = 11133)
    

    【讨论】:

      【解决方案2】:

      NOT IN 是可能的解决方案之一,但您的查询也过于复杂。 应该只是

      SELECT title FROM crs
      WHERE title NOT IN (SELECT title FROM crsstu WHERE regnum = 11131)
      

      也可以用NOT EXISTS完成

      SELECT a.title FROM crs a
      WHERE NOT EXISTS (SELECT * FROM crsstu b WHERE a.Title = b.Title AND b.regnum = 11131)
      

      LEFT JOIN

      SELECT * FROM crs a
      LEFT JOIN crsstu b ON a.Title = b.Title AND b.regnum = 11131
      WHERE b.regnum IS NULL
      

      SQLFiddle DEMO

      【讨论】:

        【解决方案3】:

        使用 Join 会更好:

        select title,regnum
        from crs as a join crsstu as b
        on a.title = b.title
        where b.regnum != 11133
        and a.title NOT IN (select title 
                        from crsstu 
                        where registrationnumber = 11133)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-31
          • 2014-09-18
          • 1970-01-01
          • 2016-10-22
          • 1970-01-01
          • 2020-12-31
          • 1970-01-01
          • 2018-05-09
          相关资源
          最近更新 更多