比较同一个表中的行

时间:2014-12-22 15:25:49

标签: sql

我的查询结果如下所示

+-------------------+
| id | c1 | c2 | c3 |
+-------------------+
| 1  | x  | y  | z  |
+----+----+----+----+
| 1  | x  | y  | z1 |
+----+----+----+----+
| 2  | a  | b  | c  |
+----+----+----+----+
| 2  | a1 | b  | c1 |
+-------------------+

我只需要获取具有C1和c2值的记录,这些记录对于相同的id不同。

对于上面的例子,结果应为

+-------------------+
| id | c1 | c2 | c3 |
+-------------------+
| 2  | a  | b  | c  |
+----+----+----+----+
| 2  | a1 | b  | c1 |
+-------------------+

您可以帮忙查询。

4 个答案:

答案 0 :(得分:4)

将表连接到自身应该可行。我假设您认为C1 C2不同,给出您发布的示例结果。

SELECT 
  t1.id,
  t1.c1,
  t1.c2,
  t1.c3
FROM
  your_table t1 
      INNER JOIN your_table t2 ON t1.id = t2.id
WHERE
  t1.c1 <> t2.c1 OR
  t1.c2 <> t2.c2

SQLFiddle

答案 1 :(得分:3)

这将为您提供任何与其他行不同的行。但是,如果您有3行,则可能无法正常工作。

SELECT t1.*
FROM someTable t1, someTable t2
WHERE t1.id = t2.id
   AND  (t1.c1 != t2.c1 OR t1.c2 != t2.c2)

修改

如果您只想要与具有相同ID的任何其他行不同的行,则在这种情况下第一个查询将不起作用:

+-------------------+
| id | c1 | c2 | c3 |
+-------------------+
| 1  | x  | y  | z  |
+----+----+----+----+
| 1  | x  | y  | z1 |
+----+----+----+----+
| 2  | a  | b  | c  |
+----+----+----+----+
| 2  | a1 | b  | c1 |
+----+----+----+----+
| 2  | a1 | b  | c3 |
+-------------------+

你会得到:

+-------------------+
| id | c1 | c2 | c3 |
+-------------------+
| 2  | a  | b  | c  |
+----+----+----+----+
| 2  | a1 | b  | c1 |
+----+----+----+----+
| 2  | a1 | b  | c3 |
+-------------------+

我认为这是错误的。在这种情况下,您将需要以下内容:

SELECT t2.*
FROM
(
    SELECT id, c1, c2
    FROM someTable
    GROUP BY id, c1, c2
    HAVING COUNT(*) = 1
) t1
JOIN someTable t2 ON t2.id = t1.id 
        AND t2.c1 = t1.c1
        AND t2.c2 = t1.c2

答案 2 :(得分:0)

如果我正确地理解了这个问题,我认为@MattGibson的答案是正确的,但如果订单很重要,则需要order by子句(按id排序)。

答案 3 :(得分:-2)

试试这个:

SELECT * FROM myTable WHERE ID 
IN(SELECT ID FROM myTable GROUP BY ID HAVING COUNT(ID)>1)