在同一列上使用多个 WHERE 条件进行选择

SELECTING with multiple WHERE conditions on same column(在同一列上使用多个 WHERE 条件进行选择)
本文介绍了在同一列上使用多个 WHERE 条件进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想我可能在这里忽略了一些明显/简单的东西...但我需要编写一个查询,该查询仅返回与同一列上的多个条件匹配的记录...

Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...

我的表是一个非常简单的链接设置,用于将标志应用到用户......

My table is a very simple linking setup for applying flags to a user ...

ID   contactid  flag        flag_type 
-----------------------------------
118  99         Volunteer   1 
119  99         Uploaded    2 
120  100        Via Import  3 
121  100        Volunteer   1  
122  100        Uploaded    2

等...在这种情况下,您会看到联系人 99 和 100 都被标记为志愿者"和已上传"...

etc... in this case you'll see both contact 99 and 100 are flagged as both "Volunteer" and "Uploaded"...

我需要能够做的是仅返回那些与通过搜索表单输入的多个条件匹配的 contactid...contactid 必须匹配所有选择的标志...在我的脑海中,SQL 应该类似于:

What I need to be able to do is return those contactid's ONLY that match multiple criteria entered via a search form...the contactid's have to match ALL chosen flags... in my head the SQL should look something like:

SELECT contactid 
 WHERE flag = 'Volunteer' 
   AND flag = 'Uploaded'...

但是……什么也没有返回……我在这里做错了什么?

but... that returns nothing... What am I doing wrong here?

推荐答案

你可以使用 GROUP BYHAVING COUNT(*) = _:

SELECT contact_id
FROM your_table
WHERE flag IN ('Volunteer', 'Uploaded', ...)
GROUP BY contact_id
HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list

(假设 contact_id, flag 是唯一的).

(assuming contact_id, flag is unique).

或者使用连接:

SELECT T1.contact_id
FROM your_table T1
JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded'
-- // more joins if necessary
WHERE T1.flag = 'Volunteer'

如果标志列表很长并且有很多匹配项,第一个可能会更快.如果标志列表很短并且匹配项很少,您可能会发现第二个更快.如果性能是一个问题,请尝试对您的数据进行测试,看看哪个效果最好.

If the list of flags is very long and there are lots of matches the first is probably faster. If the list of flags is short and there are few matches, you will probably find that the second is faster. If performance is a concern try testing both on your data to see which works best.

这篇关于在同一列上使用多个 WHERE 条件进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)