简体   繁体   English

MySQL查询-获取不同的值

[英]MySQL Query - Getting distinct values

There is a table "T" that contains data as shown below: 有一个包含数据的表“ T”,如下所示:

A   B
---------
3    5   
4    6      
7    10 
8    5 
9    12 
3    6
3    7
8    7

Assuming a given input set of {3,8} as values for A, how to retrieve all distinct values of B for which all values in the input set has an entry? 假设给定的输入集{3,8}作为A的值,如何检索B的所有不同值,其中输入集中的所有值都有一个条目?

B
---
5
7

EDIT: I think the question is not clear enough. 编辑:我认为问题还不够清楚。 I want values in B which have a record with all values in the given set as a value for column A. So, B=6 will not be included since there is no record with A=8 and B=6. 我希望B中的值具有记录,该记录中具有给定集合中的所有值作为A列的值。因此,将不包括B = 6,因为不存在A = 8和B = 6的记录。 Hope this makes it clear! 希望这清楚!

SELECT DISTINCT B 
FROM my_table WHERE A IN (3,8)

EDIT: 编辑:

SELECT B FROM AB WHERE A = 3
INTERSECT
SELECT B FROM AB WHERE A = 8

INTERSECT give you the rows which occurs in both resultsets. INTERSECT为您提供在两个结果集中出现的行。

2nd EDIT: 第二次编辑:

SELECT B,COUNT(B) 
FROM AB WHERE A IN (3,8) 
GROUP BY B 
HAVING COUNT(B) = 2

You should however modify this in two places: in IN arguments and on the end, in COUNT(B) = ?. 但是,您应该在两个地方进行修改:在IN参数中,最后在COUNT(B)=?中。 ? should be equal the number of the arguments. 应该等于参数个数。 I hope this will help. 我希望这将有所帮助。

3rd EDIT: 第三编辑:

SELECT B,COUNT(B) 
FROM 
(
    SELECT DISTINCT A, B FROM AB
) x
WHERE A IN (3,8) 
GROUP BY B 
HAVING COUNT(B) = 2

This will avoid the duplicate entries problem. 这样可以避免重复输入的问题。

Basically, you can create two subqueries where you filter out only the rows that are candidates for matching (ie A is either 3 or 8). 基本上,您可以创建两个子查询,在其中仅过滤出匹配候选行(即A为3或8)。 Then join those rows with each other on the value of B, and any matching rows will be what you're looking for. 然后将这些行彼此连接到B的值上,任何匹配的行都将成为您想要的。 I'm not 100% certain of the syntax for MySQL, but I believe this will work: 我不太确定MySQL的语法,但是我相信这会起作用:

SELECT * FROM (SELECT * FROM T WHERE A = 3) t3 INNER JOIN (SELECT * FROM T WHERE A = 8) t8 ON t3.B = t8.B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM