【问题标题】:SQL select statement in where clausewhere 子句中的 SQL 选择语句
【发布时间】:2015-07-25 21:17:48
【问题描述】:

您好,我正在尝试执行查询,但似乎无法正确执行。

SELECT *
FROM   table
WHERE  id IN (SELECT *
              FROM   table
              WHERE  description = 'A')
AND description = 'B' 

上面是我得到的查询,select * from table where description = A 在单独运行时按预期工作我只需要使 where 子句工作,这样我就可以看到任何具有 A 和 B 描述的 id。

【问题讨论】:

  • 描述不能同时使用“A”和“B”。只是“A”或“B”。
  • 问题是可能有多个相同id的记录,它们可能包含A或B的描述,所以嵌套的select语句只找到描述为A的id,然后我想获取这些 id 并找出其中有多少也有 B 的描述。我认为@SimonPJ 解决方案应该为我做这个?
  • 好的,我明白了。我虽然 id 是唯一的。我认为@SimonPJ 解决方案是正确的答案。

标签: sql sql-server sql-server-2008 select where-clause


【解决方案1】:
SELECT distinct AnaTablo.Id , AnaTablo.FirmaAdi , AnaTablo.FirmaId , AnaTablo.KayitTarihi ,
users.Email Personel,   (SELECT top 1 sabitler.Ayar from tblSabitAyarlar sabitler WHERE sabitler.Tur = 29 and sabitler.Deger in 
(SELECT top 1 IslemId from tblEFaturaTakipIslem Islem WHERE AnaTablo.Id = Islem.EFaturaTakipId order by KayitTarihi desc))YapilanIslem,
AnaTablo.Eposta , AnaTablo.Aciklama
from tblEFaturaTakip AnaTablo left join AspNetUsers users on AnaTablo.PersonelId  = users.Id

【讨论】:

    【解决方案2】:

    当我假设您只需要 id 列时,您将从子查询中获得多个列:

    SELECT *
    FROM   table
    WHERE  id IN (SELECT id
              FROM   table
              WHERE  description = 'A')
       AND description = 'B' 
    

    【讨论】:

    • 这似乎正是我所追求的!谢谢一百万
    【解决方案3】:

    试试这个:

    SELECT *
    FROM table
    WHERE description IN ('A', 'B')
    

    【讨论】:

      【解决方案4】:

      应该是:

      select * from table where id in (select id from table where description = 'A') and description = 'B'
      

      但是当您选择 description = 'A' 和 description = 'B' 的记录时,此查询会给您零结果,如果您想获取描述为 A 或 B 的记录,那么您应该写为

      select * from table where description = 'A' or description = 'B'
      

      select * from table where description in ('A','B')
      

      【讨论】:

        【解决方案5】:

        不需要where子句中的select

        SELECT *
        FROM table
        WHERE id IN ('A', 'B')
        

        【讨论】:

        • 我认为,OP 的查询将获取映射到“A”和“B”的id。但在您的情况下,它将获取映射到“A”或“B”的 id。该查询中的错误是子查询中的select *
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-26
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多