mysql intersect用法格式,模仿array_intersect在MySQL中

本文介绍了如何使用SQL聚合查询来找出多个条件下的交集结果。通过一个例子展示了如何从一个表格中选取特定列,当列1等于特定单词时,找出在所有查询中都出现的结果。解决方案涉及到了GROUP BY和HAVING子句,可以灵活地适用于任意数量的列1值。
摘要由CSDN通过智能技术生成

I have a table like this:

Col1 Col2

word1 872

word1 333

word2 631

word3 982

word3 111

word4 111

word5 631

word6 333

word6 453

I would like to receive the results of multiple SELECTs, but only those results which occur in all results. For example, if I am searching for SELECT col2 FROM table WHERE col1='word1' and SELECT col2 FROM table WHERE col1='word6', I want to join these two statements together to have a single MySQL statement which will return only the results that occur in both of the above example queries. (The same as array_intersect works in PHP.)

I need a single query that will do this for any number of col1 words.

Sorry, if I haven't explained very well. It was difficult to explain.

解决方案

The best approach to this problem is to use aggregation:

select col2

from t

group by col2

having max(col1 = 'word1') = 1 and

max(col1 = 'word2') = 1

This easily generalizes to more words.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值