SQL Query用于检索列中具有条件值的行

时间:2012-06-07 16:26:27

标签: sql

我不知道此问题是否也曾被提出过。如果是这样,请指示我链接。

我的表格有三列nametypedateType只能是4个值A,B,C和D

我想获取所有类型为A,B或C的记录,但条件是只有在同一名称的类型为D时才应该获取。

e.g。让我们考虑一下这个表

Name      type    Date 
abc        A       5/7
abc        B       6/7
abc        D       7/7

xyz        A       5/7
xyz        D       6/7

lmn        A       5/7
lmn        B       6/7
lmn        C       7/7

所以这里的交易我需要以下结果集

ABC 5/7
ABC 6/7
XYZ 5/7

因为ABC和XYZ有一个type D,所以显示了ABC和XYZ的其他记录。由于lmn没有type D,因此它不包含在结果集中。

3 个答案:

答案 0 :(得分:3)

要测试是否存在记录,您只需使用where exists

即可
select * from mytable t1 where exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);

这可能是自我解释的,但这里有一个参考:http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

如果要排除D记录,请执行以下操作:

select * from mytable t1 where t1.type<>"D" and exists (
     select * from mytable t2 where t1.Name=t2.Name and t2.type="D"
);

答案 1 :(得分:1)

试试这个:

SELECT Name, Date
FROM MyTable as mt
WHERE type != 'D'
AND EXISTS
(
   SELECT * FROM MyTable as mt2
   WHERE mt2.type = 'D' and mt2.name = mt.name
)

您正在选择所有类型不等于D并且具有匹配名称的记录,其中类型IS等于D

答案 2 :(得分:0)

create view all_D as select name from your_table where type=D
select * from your_table where type<>D and name in (select * from all_D) 

你甚至可以这样做,而不是那个视图,你突然把这个查询放在“不在”之后的括号中