1

我有一张桌子,我想检查一列的所有值是否相同。

以下是我表中的条目。

两列

rid,value
(1,1)
(1,1)
(2,1)
(2,0)
(2,0)
(3,0)
(3,0)
(3,0)

我想要查询,因为它的所有值都是 1,所以它给了我 rid 1。rid 1 的所有记录都有值 1,并且 rid 2 和 3 的所有值都不是 1,所以它们不应该被选中。

4

2 回答 2

2

使用 group by 和 have 可以得到你想要的:

    SELECT rid, value
    FROM my_table
    GROUP BY rid
    HAVING COUNT( distinct value) = 1 

更新

根据评论,过滤值会得到结果:

SELECT *
FROM
    (
    SELECT rid, value
    FROM my_table
    GROUP BY rid
    HAVING COUNT( distinct value) = 1 
    ) AS T1
WHERE value = 1

如果值只有 1 或 0,那么你可以这样做:

    SELECT rid, value
    FROM my_table
    GROUP BY rid
    HAVING COUNT( * ) = SUM(value)
于 2014-12-07T08:50:18.257 回答
0

你可以这样做:

  CREATE TABLE my_table (
  id varchar(255),
  col_value varchar(255)
);
INSERT INTO my_table 
  VALUES
         ('1','1'),
         ('1','1'),
         ('2','1'),
         ('2','1'),
         ('2','1'),
         ('2','4'),
         ('3','1'),
         ('3','1');

查询选择:

SELECT src.* FROM
(
    SELECT DISTINCT t1.* FROM my_table AS t1 
) AS src
WHERE src.id NOT IN(
        SELECT test.id
        FROM 
        (
             SELECT DISTINCT t1.* FROM my_table AS t1 
        ) AS test
        GROUP BY test.id
        HAVING COUNT(*) > 1
 )

在这里摆弄

于 2014-12-07T06:58:42.110 回答