SQL where条件在我的情况下删除重复记录

时间:2013-04-03 19:07:01

标签: mysql sql database

有前端系统,它在表中输入这种类型的数据,我没有控制。我查询结果的表格:

Row|    id| entity_code|    entity_value
1            1      Null        22
2            2      Null        28
3            3      Null        32
4            3   Test Entity  Test Entity
5            4      Null        22

在上面的查询返回表示例中,前端用新记录输入“Test Entity”,而不是在id = 3上覆盖

实际上表是非常复杂的n有十几个连接,我想要查询的WHERE条件我们可以删除 如果'entity_code'列为空且没有其他记录具有相同的'Entryid'则ok(第1,2 n 4行)但如果'entity_code'列不为null(第4行),则其他具有相同'id'的记录为exsist(例如第3行。 条件结果如下:

Row|  Entry|    entity_code|    entity_value
1        1              Null        22
2        2              Null        28
3        3           Test Entity    32
4        4              Null        22

我需要那个显示这种结果的Condtion。

1 个答案:

答案 0 :(得分:2)

如果我理解你的逻辑,这应该会给你正确的结果:

SELECT
  e1.min_row row,
  e1.id,
  e2.max_value,
  e.entity_value
FROM
  entity e INNER JOIN (
    SELECT
      id,
      MIN(row) min_row
    FROM
      entity
    GROUP BY
      id
    ) e1
  ON e.row = e1.min_row
  INNER JOIN (
    SELECT
      id,
      MAX(entity_code) max_value
    FROM
      entity
    GROUP BY
      id
    ) e2
  ON e1.id = e2.id

请参阅小提琴here

这也更简单,适用于您的示例数据,但我不确定它是否适用于您的实际数据(取决于您的数据库结构):

SELECT
  e1.Row,
  e1.id,
  e2.entity_code,
  e1.entity_value
FROM
  entity e1 LEFT JOIN entity e2
  ON e2.entity_code IS NOT NULL
     AND e1.id = e2.id AND e1.Row!=e2.Row
WHERE
  e1.entity_code IS NULL