我正在尝试在其中一列中选择具有特定值的记录。请考虑以下示例:
NAME VALUETEST
rec1 val1
rec2 val1
rec3 val1
rec1 test123
rec1 test1234
rec2 test1234
这里我希望只选择那些valuetest列值为val1,test123和test1234的记录,即rec1。我尝试过以下简单的选择查询,但它没有给我想要的结果
查询:select * from temp where valuetest = all ('val1','test123','test1234');
答案 0 :(得分:1)
这应该这样做:
SELECT name, COUNT(*)
FROM temp
WHERE valuetest IN ('val1','test123','test1234')
GROUP BY name
HAVING COUNT(*) = 3;
它将检索与NAME
,val1
和test123
匹配的所有test1234
。
如果您确实需要所有行而不仅仅是名称,则应使用JOIN
:
SELECT *
FROM temp
INNER JOIN (
SELECT name, COUNT(*)
FROM temp
WHERE valuetest IN ('val1','test123','test1234')
GROUP BY name
HAVING COUNT(*) = 3
) USING(name);
此外,此方法仅扫描表格两次,而不管条件中的值的数量是多少('val1','test123','test1234',...
)
答案 1 :(得分:0)
此查询是否能为您提供所需的结果?
select *
from temp
where valuetest in ('val1', 'test123', 'test1234');
答案 2 :(得分:0)
从temp中选择*,其中valuetest IN ('val1','test123','test1234');
或使用可以使用
从temp中选择*,其中valuetest = ANY ('val1','test123','test1234');
使用任意代替全部,因为全部会尝试匹配单个记录的所有三个值
答案 3 :(得分:0)
我怀疑这就是你想要的:
select name from temp where valuetest = 'val1'
intersect
select name from temp where valuetest = 'test123'
intersect
select name from temp where valuetest = 'test1234'
如果您希望从表中选择的列数多于名称,请运行:
select * from temp where name in(
select name from temp where valuetest = 'val1'
intersect
select name from temp where valuetest = 'test123'
intersect
select name from temp where valuetest = 'test1234')