删除一列中具有多个唯一值的行

时间:2017-11-23 06:35:33

标签: sql postgresql

我有两个表table1table2 - 我希望将这些表与删除的任何重复emp + carno行合并。例如下面 - 需要删除empmike的行,因为mikecarno中有多个唯一table1。同样,需要删除empsara的行,因为saracarnotable1之间有多个唯一table2

表1

+------+---------+
| emp  |   carno |
+------+---------+
| mike |  mh01   |
| sara |  mh02   |
| luke |  mh01   |
| mike |  mh04   |
+------+---------+

表2

+------+---------+
| emp  |   carno |
+------+---------+
| dave |  mh01   |
| sara |  mh06   |
| nite |  mh07   |
+------+---------+

输出

+------+---------+
| emp  |   carno |
+------+---------+
| luke |  mh01   |
| dave |  mh01   |
| nite |  mh07   |
+------+---------+

3 个答案:

答案 0 :(得分:2)

在内部查询中使用union all来组合来自两个表和aggregation以及having count(emp) = 1的数据,以在外部查询中过滤掉具有多个记录的员工,如下所示。

select t.emp, min(t.carno) as carno from 
(
select * from table1
union all
select * from table2
) t
group by t.emp
having count(t.emp) = 1
order by carno;

<强>结果:

emp     carno
--------------
dave    mh01
luke    mh01
nite    mh07

<强> DEMO

<强>更新

您可以使用INSERT INTO tablex(emp, carno) SELECT .....将输出插入表格

insert into tablex (emp, carno)
select t.emp, min(t.carno) as carno from 
(
select * from table1
union all
select * from table2
) t
group by t.emp
having count(t.emp) = 1
order by carno;

<强> INSERT-SELECT DEMO

答案 1 :(得分:1)

使用具有适当逻辑的INSERT INTO ... SELECT。我在这里使用的基本策略是将两个表联合在一起,然后应用COUNT作为分析函数来确定哪些员工的数量大于一。然后,将联合结果限制为仅包括他或她出现一次的员工记录。

INSERT INTO output (emp, carno)
SELECT emp, carno
FROM
(
    SELECT emp, carno, COUNT(*) OVER (PARTITION BY emp) cnt
    FROM
    (
        SELECT emp, carno FROM table1
        UNION ALL
        SELECT emp, carno FROM table2
    ) t1
) t2
WHERE cnt = 1;

以下是外部选择的输出:

enter image description here

修改

@zarruq的答案比这个答案更有效,因为它消除了一个子查询。但我的方法很容易适应,以过滤任何基数的员工,而不会改变绩效。

Demo

答案 2 :(得分:0)

  

用于从具有不同键的多个表中删除

  delete a,b from table1 a innerjoin table2 b on b.carno != a.carno where a.emp ='mike' or b.emo = 'sara' 

你可以通过选择查询

使用变量而不是静态
Select a.emp as name1,b.emp as name2 from table1 a innerjoin table2 b on b.carno != a.carno

这里你需要执行查询并获取name1和name2并将其保存到变量

delete a,b from table1 a innerjoin table2 b on b.carno != a.carno where a.emp ='$name1' or b.emo = '$name2' 
  

表示同一表中的多个条目

     

首先选择

select count(*) as total from table1 where emp ='mike'; //or emp = '$yourvariable'

here u need to execute query and get total as count
if(total!=1)
{
delete a from table1 a where name ="mike"
}