【问题标题】:delete rows when a column has conditions in two tables当列在两个表中有条件时删除行
【发布时间】:2020-02-24 20:54:24
【问题描述】:

我有两张桌子,table_atable_b。 我需要从table_a 中删除所有行,并使用以下内容,这对我有用(直到 and 语句): (etid是一个整数,在table_a

delete m1 
from table_a m1
inner join table_a m2 on m1.etid = m2.etid and m1.id <> m2.id
where m1.gid = 198 and (here i need to make sure that each row with etid that fulfills above criteria and will be deleted, is also of type 'product', info which is stored in table_b)

table_b 有两列: nidtype

type 列的不同值有两个:'product''raw'
nid 是存储在table_aetid 列中的整数。

我想我必须添加另一个连接,还有 in 语句,以便只选择适当的行......上面的 sn-p 应该如何更改?就执行时间的速度而言,我还想找出最高效的方法

https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=c16369b42847fbfb9a609e613945fc01

上面的示例数据。

预期输出

+----+------+---------+-----+
| id | etid |  title  | gid |
+----+------+---------+-----+
| 1  | 120  | Title1  | 198 | <-row that must be deleted
| 2  | 121  | Title2  | 55  |
| 3  | 120  | Title1  | 674 |
+----+------+---------+-----+

最终输出

+-----+------+---------+-----+
| id  | etid |  title  | gid |
+-----+------+---------+-----+
| 2   | 121  | Title2  | 55  |
| 3   | 120  | Title1  | 674 |
+-----+------+---------+-----+

【问题讨论】:

  • 样本数据和预期输出会有所帮助。
  • 当然,现在就准备好

标签: mysql


【解决方案1】:

您需要再次加入table_b

delete m1 
from table_a m1 
inner join table_a m2 on m1.etid = m2.etid and m1.id <> m2.id
inner join table_b b on b.nid = m1.etid
where m1.gid = 198 and b.type = 'product'

【讨论】:

  • 我认为这是我所缺少的,另一个加入,谢谢
【解决方案2】:

你可以试试下面的查询。

DELETE M1 ,TABLE_A
FROM  M1
INNER JOIN TABLE_A M2 ON M1.ETID = M2.ETID AND M1.ID <> M2.ID
WHERE M1.GID = 198 AND M1.ETID IN (SELECT NID FROM TABLE_B TYPE= 'product');

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多