Mysql select query其中列有两个值

时间:2018-06-11 20:26:52

标签: mysql

我在MySQL有一张桌子。在这里,我有一个名为devicetest_Id的columna。

+-------+---------+
|test_id|   device|
+-------+---------+
| test_1|   Win PC|
| test_1|     Xbox|
| test_2|  Windows|
| test_3|   Win PC|
+-------+---------+

我想选择test_Id,其中device同时为Win PCXbox。我在下面做了

select test_id from table where device in ('Win PC', 'Xbox');

我的结果低于结果。

+----------+
| test_id  |
+----------+
| test_1   |
| test_3   |
| test_1   |
+----------+

但我希望结果像

+----------+
| test_id  |
+----------+
| test_1   |
| test_1   |
+----------+

我该怎么做?

4 个答案:

答案 0 :(得分:3)

实现结果的最简单查询,一个独特的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

如果我们想要返回单个行,我们可以将其用作内联视图,并对外表执行JOIN。像这样:

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')

另一种选择是使用EXISTS相关子查询

 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'
               )

还有其他查询模式可以达到相同的效果。

答案 1 :(得分:2)

如果您只是想知道test_id是否同时拥有Xbox和PC,您可以执行以下操作:

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

答案 2 :(得分:1)

select test_id 
from table 
where device = 'Win PC'
AND test_id IN (SELECT test_id 
from table 
where device = 'Xbox')

答案 3 :(得分:0)

我没有测试过,但您应该尝试此查询

SELECT table_pc.test_id 
FROM table AS table_pc 
INNER JOIN table AS table_xb ON (table_xb.test_id = table_pc.test_id)
WHERE table_pc.device = 'Win PC' 
AND table_xb.devide = 'Xbox'
GROUP BY table_pc.test_id