Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

MySQL select query ANDed multiple condition of same column

I have the below test table with the following rows in the table.

table: test_set(id (pk), pid int, fc int, fl int)

pid      fc    fl
1        7     30
1        8     31
1        9     35
2        7     39
2        8     40

Now if I run

SELECT pid FROM test_set WHERE fl=30 OR fl=35 GROUP BY pid;
#Result :
pid
---
1

As expected but if I want to run

SELECT pid FROM test_set WHERE fl=30 AND fl=35 GROUP BY pid;
#Result :
result set (0) # Nothing matched!

This is too as expected but I want to go beyond expectation here. My logic here is that fl=30 and fl=35 both have pid=1 in common i.e. when they are intersected they yeilds pid=1

So to be specific I need the result of multiple values of fl column that have one or more pid in common.

I have already read this this and commented there too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What about:

SELECT pid, COUNT(DISTINCT fl) AS count, GROUP_CONCAT(DISTINCT fl) list
FROM test_set
GROUP BY pid HAVING count > 1;

?

Output:

+------+-----------+------------------+
| pid  | count     | list             |
+------+-----------+------------------+
|    1 |         3 | 30,31,35         |
|    2 |         2 | 39,40            |
+------+-----------+------------------+

Given two fl values:

SELECT pid, COUNT(DISTINCT fl) AS count
FROM test_set
WHERE fl IN (30, 35)
GROUP BY pid HAVING count = 2;

Output:

+------+-------+
| pid  | count |
+------+-------+
|    1 |     2 |
+------+-------+

Given three fl values:

SELECT pid, COUNT(DISTINCT fl) AS count
FROM test_set
WHERE fl IN (30, 31, 35)
GROUP BY pid HAVING count = 3;

Output:

+------+-------+
| pid  | count |
+------+-------+
|    1 |     3 |
+------+-------+

It's good to have indexes on pid and fl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...