简体   繁体   English

如何编写一个SQL查询来检索同一列上具有2个条件的所有行

[英]How to write a SQL Query which retrieves all the rows with 2 condition on the same column

How to write a SQL Query which retrieves all the rows with 2 condition on the same column? 如何编写一个SQL查询来检索同一列上具有2个条件的所有行?

I got a table with a column called type. 我有一个表,其中有一列称为类型。 What I want to do is to list up all type of value "name". 我要做的是列出所有类型的值“名称”。 But the type column also has a value called text. 但是type列也有一个称为text的值。 So what I want to do is to list up all type of names, that has type text value. 所以我想做的是列出所有具有类型文本值的名称。

How can I achieve this? 我该如何实现?

ID     Type     Value
1      Name    Name1
1      Text    "Hello"
2      Text    "Hello test"
2      Name    Name2
3      Name    Name3
4      Name    Name4
5      Name    Name5

I only want to return name value that has a type text. 我只想返回具有文本类型的名称值。 The table has two types, what I want to do it to only return all of the type "Name" which has a type text 该表有两种类型,我想做的就是只返回具有文本类型的所有“名称”类型

Expected result: 预期结果:

ID     Type     Value
1      Name    Name1
2      Name    Name2

Because these two are the only one with type "text" with a value. 因为这两个是唯一带有值的“文本”类型的两个。

Is this what you want? 这是你想要的吗?

Select * from
(
select a.* from tbl a join tbl b
on a.ID = b.ID
where
a.Type = 'Name' and b.Type = 'Text'
) tb
where tb.Type = 'Name'

Do a self join: 进行自我加入:

select t1.*
from tablename t1
join tablename t2 on t1.id = t2.id
where t1.Type = 'Name'
  and t2.Type = 'Text'

I would use exists : 我会用exists

select t.*
from t
where t.type = 'Name' and
      exists (select 1
              from t t2
              where t2.id = t.id and t2.type = 'Text'
             );

I would use join if I wanted to use any values from the "text" row. 如果要使用“文本”行中的任何值,我将使用join However, if I only want the "name" row, then I think exists is a more direct translation of the logic. 但是,如果我只想要“名称”行,那么我认为exists是一种更直接的逻辑翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM