I am trying to get from a table those values in column1, that have some values in column2.
我试图从表中获取column1中的值,这些值在column2中有一些值。
For example, I want to get A because it has "1,2,3". (Expected Output of select: A)
例如,我想获得A,因为它有“1,2,3”。 (预期产出的选择:A)
---
A|1
A|2
A|3
A|4
B|1
B|3
---
This is what I've tried
这就是我尝试过的
SELECT * FROM sample_table WHERE Col2 in (1,2,3) GROUP BY col1
I understand perfectly it won't work, since I am just putting the condition that column 2 must have one of those values, and then I group them by Col1, so It will take (A,1),(A,2),(A,3),(B,1),(B,2) -> group them by Col1 and give me (A) and (B)
我完全理解它不会起作用,因为我只是把第2列必须具有其中一个值的条件,然后我将它们按Col1分组,所以它需要(A,1),(A,2), (A,3),(B,1),(B,2) - >按Col1分组给我(A)和(B)
I really have no clue how I could force it to have ALL the 3 values
我真的不知道如何强制它拥有所有3个值
Here is the fiddle to try it
这是尝试它的小提琴
NOTE
注意
Please feel free to edit the post in order to make it more understandable, I have tried my best, but I know its not very well explained, specially the title
请随时编辑帖子,以使其更容易理解,我已尽力了,但我知道它不是很好解释,特别是标题
Thank you very much
非常感谢你
2 个解决方案
#1
6
You can use the HAVING()
clause :
您可以使用HAVING()子句:
SELECT col1
WHERE Col2 in (1,2,3)
GROUP BY col1
HAVING COUNT(col2) = 3
This will show only results that have 3 values , and since you filtered only for 1,2,3
, if there are 3, it those 3.
这将仅显示具有3个值的结果,并且由于您仅针对1,2,3进行过滤,如果有3个,则为3。
Note : If the values on col2 are not distinct , E.G. it's possible for this data to appear:
注意:如果col2上的值不明显,则E.G.这些数据可能会出现:
A | 1
A | 1
A | 2
Then add DISTINCT
inside the parentheses of the count.
然后在计数的括号内添加DISTINCT。
#2
0
You could try to play with HAVING
and GROUP_CONCAT
:
您可以尝试使用HAVING和GROUP_CONCAT:
SELECT COL1
FROM sample
GROUP BY COL1
HAVING GROUP_CONCAT(DISTINCT COL2 ORDER BY COL2 ASC) LIKE '%1,2,3%'
#1
6
You can use the HAVING()
clause :
您可以使用HAVING()子句:
SELECT col1
WHERE Col2 in (1,2,3)
GROUP BY col1
HAVING COUNT(col2) = 3
This will show only results that have 3 values , and since you filtered only for 1,2,3
, if there are 3, it those 3.
这将仅显示具有3个值的结果,并且由于您仅针对1,2,3进行过滤,如果有3个,则为3。
Note : If the values on col2 are not distinct , E.G. it's possible for this data to appear:
注意:如果col2上的值不明显,则E.G.这些数据可能会出现:
A | 1
A | 1
A | 2
Then add DISTINCT
inside the parentheses of the count.
然后在计数的括号内添加DISTINCT。
#2
0
You could try to play with HAVING
and GROUP_CONCAT
:
您可以尝试使用HAVING和GROUP_CONCAT:
SELECT COL1
FROM sample
GROUP BY COL1
HAVING GROUP_CONCAT(DISTINCT COL2 ORDER BY COL2 ASC) LIKE '%1,2,3%'