SQL查询列的依赖关系

时间:2011-06-17 05:53:40

标签: sql

我必须为一个表写一个查询,其中我有两列可以说是id1和id2。在此查询中,我必须确保id2可以为单个id1提供最多三个值。我尝试过使用此查询:

select id1,id2
from table
group by id1,id2
having count(id2)<=3

我没有通过此查询获得结果。有哪些修改?

4 个答案:

答案 0 :(得分:1)

如果(id1id2)对不是唯一的,那么可能是这样的:

SELECT t.id1, t.id2
FROM atable t
  INNER JOIN (
    SELECT id1
    FROM atable
    GROUP BY id1
    HAVING COUNT(DISTINCT id2) <= 3
  ) g ON t.id1 = g.id1
GROUP BY t.id1, t.id2

但是如果对 唯一,则外部查询不需要GROUP BY,内部查询不需要DISTINCT:

SELECT t.id1, t.id2
FROM atable t
  INNER JOIN (
    SELECT id1
    FROM atable
    GROUP BY id1
    HAVING COUNT(id2) <= 3
  ) g ON t.id1 = g.id1

答案 1 :(得分:0)

你的问题很难理解......也许这个?

select id1, id2 from table where (select count(id2) from table where id1 = id1) <= 3

答案 2 :(得分:0)

请试试这个......

选择a.id1,a.id2
来自 table_name a,(select count(1),table1中的id1由id1计数的组(*)&lt; = 3)b
其中a.id1 = b.id1
按id1排序

答案 3 :(得分:0)

更典型的是测试失败业务规则的行,例如

SELECT DISTINCT *
  FROM Table1
 WHERE EXISTS (
               SELECT T1.id1
                 FROM Table1 AS T1
                WHERE T1.id1 = Table1.id1
                GROUP 
                   BY T1.id1
               HAVING COUNT(*) > 3
              );

我们的想法是,一旦您确定哪些行违反了业务规则并且您已经清除了错误数据,您就希望设置一个约束来确保未来不违反规则,例如: (注意相同的查询结构):

ALTER TABLE Table1 ADD
   CONSTRAINT atmost_three_id2_values_for_a_single_id1
      CHECK (NOT EXISTS (
                         SELECT T1.id1
                           FROM Table1 AS T1
                          WHERE T1.id1 = Table1.id1
                          GROUP 
                             BY T1.id1
                         HAVING COUNT(*) > 3
                        ));

可悲的是,your SQL product of choice probably does not support subqueries in CHECK constraints。您可以通过添加序列号列来“设计”对表级约束的需求,从而允许您使用常见的UNIQUE和列级CHECK约束,例如

CREATE TABLE Table1
(
 id1 INTEGER NOT NULL, 
 id2 INTEGER NOT NULL, 
 UNIQUE (id1, id2), 
 seq INTEGER DEFAULT 1 NOT NULL
    CHECK (seq BETWEEN 1 AND 3), 
 UNIQUE (id1, seq)
);