SQL:当PK等于同一字段中两个不同行中的两个特定值时返回值

时间:2015-03-11 10:02:11

标签: mysql sql

我正在尝试返回SAME id在23和12中的行(这只是一个示例......我有30K记录)

ID: ASDJKGFJKBQGW Number:23
ID: ASDJKGFJKBQGW Number:12
ID: ASDJKGFJKBQGW Number:43
ID: ASDJKGFJKBQGW Number:67
ID: ASDJKGFJKBQGW Number:32

执行:select * from table where Number=23 and Number=12不会这样做。

我是否需要为ID声明变量并执行while循环?

While @ID is the same
select * from table where Number = 23 and Number = 12

由于

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题

select * from table where Number in (23, 12)

select * from table where Number = 23 or Number = 12

修改

类似的东西:

   select id from table where number in (23,12) 
   group by id
   having count(*) = 2

如果每个id的数字可以出现多次,那么您可以使用子查询

   select id from 
   ( select distinct id, number from table ) x
   where number in (23,12) 
   group by id
   having count(*) = 2

答案 1 :(得分:0)

Select * from table1
Where number in (14,23) and id in(
Select id from table1 
Where number in (14,23)
Group by id
Having count(distinct number) = 2)

内部子查询使用having子句给出确切的行数2.与不同的一起你肯定会得到这些行