从SQL查询中删除重复项

时间:2014-05-14 21:56:28

标签: mysql sql

我尝试创建一个不会返回具有相同ID的行的SQL查询。我还想指定一个主行,以便在两行具有相同ID的情况下,将返回主行。如果没有指定主行,我想返回第一行。

以下是我想要查询的数据库示例。

+----+---------+-------+
| id | primary | label |
+----+---------+-------+
| 1  |    Y    |   A   |
| 1  |         |   B   |  
| 2  |         |   C   |
| 2  |         |   D   |
| 3  |         |   E   |
+----+---------+-------+

这是我想要实现的结果的一个例子

+----+---------+-------+
| id | primary | label |
+----+---------+-------+
| 1  |    Y    |   A   |
| 2  |         |   C   |
| 3  |         |   E   |
+----+---------+-------+

我一直试图使用select distinct,但我不确定如何解决这个问题。任何帮助是极大的赞赏。谢谢!

4 个答案:

答案 0 :(得分:2)

在您的情况下,子查询比DISTINCT更合适。

尝试以下方法。以下是获得所需结果的演示:http://sqlfiddle.com/#!2/97fdd3/1/0

顺便说一下,当没有"主要"对于ID,这将选择该ID的最低标签值。正如其他人所说的那样,数据库中的顺序更可靠。

select *
  from tbl t
 where t.label = (select x.label
                    from tbl x
                   where x.primary = 'Y'
                     and x.id = t.id)
    or (not exists
        (select 1
           from tbl x
          where x.primary = 'Y'
            and x.id = t.id) and
        t.label = (select min(x.label) from tbl x where x.id = t.id))

答案 1 :(得分:1)

我可以看到你已经得到了答案,但你也可以使用常规LEFT JOIN;

SELECT * FROM mytable a 
LEFT JOIN mytable b
  ON a.id = b.id AND (
            a.label>b.label AND a.primary IS NULL AND b.primary IS NULL OR 
                                a.primary IS NULL AND b.primary='Y')
WHERE b.id IS NULL

An SQLfiddle to test with

答案 2 :(得分:0)

SELECT a.id, 
       IFNULL(primaries.primary, '') AS primary, 
       IFNULL(primaries.label, secondary.label) AS label
FROM yourTable AS a
LEFT JOIN (SELECT *
           FROM yourTable
           WHERE primary = 'Y') AS primaries
ON a.id = primaries.id AND a.label = primaries.label
LEFT JOIN (SELECT id, MIN(label) AS label
           FROM yourTable
           WHERE primary != 'Y'
           GROUP BY id) AS secondary
ON a.id = secondary.id AND a.label = secondary.label

答案 3 :(得分:0)

也许这样的事情有效(未经测试):

SELECT DISTINCT
      t1.id
     ,t2.primary
     ,t2.label
FROM table t1
    LEFT JOIN (
        SELECT id, primary, label
        FROM table
        GROUP BY id
        ORDER BY primary DESC, label ASC
        LIMIT 1
    ) t2 ON t2.id=t1.id