【问题标题】:mysql delete duplicated rows that not exist in another tablemysql删除另一个表中不存在的重复行
【发布时间】:2014-08-08 13:05:51
【问题描述】:

在医院的数据库中工作。 我有一张病人表,还有一张包含医疗记录的表。 表病历,有patient_id。 由于系统中的错误,许多患者被插入了两次或更多,具有相同的 id。 我正在尝试创建一个 mysql 查询,允许我删除/检查在患者表中重复的患者,但前提是患者 ID 不在医疗记录表中。

类似这样的:

(select * from patients group by id having count(id)>1 as p)
 where patient_id not in (select patient_id from history)

上面的查询是象征性的,它不起作用。

【问题讨论】:

    标签: mysql records


    【解决方案1】:

    选择所有不在history 中的重复patients 的方法是使用where not exists

    select p.id
    from patients p
    
    where not exists (
      select h.patient_id 
      from history h 
      where h.patient_id=p.id
    )
    group by p.id having count(p.id) > 1
    

    另一种方法是使用not in

    select id
    from patients
    
    where id not in (
      select patient_id from Posts 
      WHERE patient_id IS NOT NULL
      group by patient_id
    )
    group by id having count(id) > 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多