I have a table in MySQL
. In this I have columna called device
and test_Id
.
+-------+---------+
|test_id| device|
+-------+---------+
| test_1| Win PC|
| test_1| Xbox|
| test_2| Windows|
| test_3| Win PC|
+-------+---------+
I want to select test_Id
where device
is both Win PC
and Xbox
. I have done like below
select test_id from table where device in ('Win PC', 'Xbox');
I am getting below result.
+----------+
| test_id |
+----------+
| test_1 |
| test_3 |
| test_1 |
+----------+
But I want the result to be like
+----------+
| test_id |
+----------+
| test_1 |
| test_1 |
+----------+
How can I do that?
Find duplicate values in one column First, use the GROUP BY clause to group all rows by the target column, which is the column that you want to check duplicate. Then, use the COUNT() function in the HAVING clause to check if any group have more than 1 element. These groups are duplicate.
Find Duplicate Row values in Multiple Columns SELECT col1, col2,..., COUNT(*) FROM table_name GROUP BY col1, col2, ... HAVING (COUNT(col1) > 1) AND (COUNT(col2) > 1) AND ... In the above query, we do a GROUP BY of all the columns (col1, col2) for whom we want to find duplicates.
The simplest query to achieve the result, a distinct list of test_id:
SELECT t.test_id
FROM mytable t
WHERE t.device IN ('Win PC','Xbox')
GROUP BY t.test_id
HAVING COUNT(DISTINCT t.device) = 2
If we want to return individual rows, we could use that as an inline view, and do a JOIN to the outer table. Something like this:
SELECT d.test_id
FROM ( SELECT t.test_id
FROM mytable t
WHERE t.device IN ('Win PC','Xbox')
GROUP BY t.test_id
HAVING COUNT(DISTINCT t.device) = 2
) q
JOIN mytable d
ON d.test_id = q.test_id
WHERE d.device IN ('Win PC','Xbox')
Another alternative would be use EXISTS correlated subqueries
SELECT d.test_id
FROM mytable d
WHERE d.device IN ('Win PC','Xbox')
AND EXISTS ( SELECT 1
FROM mytable t1
WHERE t1.test_id = d.test_id
AND t1.device = 'Win PC'
)
AND EXISTS ( SELECT 1
FROM mytable t2
WHERE t2.test_id = d.test_id
AND t2.device = 'Xbox'
)
There are other query patterns that will achieve equivalent results.
select test_id
from table
where device = 'Win PC'
AND test_id IN (SELECT test_id
from table
where device = 'Xbox')
If you just want to know whether a test_id has both an Xbox and PC, you can do the following:
select test_id from
(select test_id, count(test_id) as cnt
from table
where device in ('Win PC', 'Xbox'), group by test_id)
where cnt > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With