从 SQL table 中删除 ID 是从应用于另一个 table 的条件中找到的
Delete from SQL table where ID is found from conditions applied to another table
首先,我不知道标题是否正确,但让我告诉你我想要的,我会按照建议更正。
所以,我有 2 个表:
- 表1
- ID、subid、姓名
- 表2
- ID
我想要的是删除 table2
中 ID
等于 table1
中的 subid
的任何元素,其中 table1.name
等于指定值。
如果我在 table1
中有这些元素
ID subid name
1 ... 1 ...... name1
2 ... 3 ...... name2
3 ... 2 ...... name1
4 ... 1 ...... name2
以及 table2
中的这些行
ID
1
2
3
4
我想删除table2
中ID = subid的那些元素,当name = name1时,这意味着元素1和2。
类似于:
DELETE FROM table2
WHERE ID = (SELECT subid
FROM table1
WHERE NAME = "name1")
这可能吗?
你们非常亲密。
你只需要= ANY
rather than =
as the subquery can return more than one row SQL Fiddle。
DELETE
FROM table2
WHERE ID = ANY (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
虽然这更常用 IN
来表达
DELETE
FROM table2
WHERE ID IN (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
我对您发布的查询进行了一些其他更改...
- 我总是确保子查询中的列引用使用两部分名称以避免 unfortunate surprises。
- 您应该使用单引号来分隔字符串文字,以便它在默认
QUOTED_IDENTIFIER
设置下工作,并且不会被解释为引用名为 name1
. 的列
您也可以使用连接删除,所以很有可能。
您可以先识别(待)删除的记录:
select t2.*
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
然后执行删除:
delete t2
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
@eckes 查看我的 fiddle 以及我用来查看它是否有效的语法:http://sqlfiddle.com/#!6/260a5
首先,我不知道标题是否正确,但让我告诉你我想要的,我会按照建议更正。 所以,我有 2 个表:
- 表1
- ID、subid、姓名
- 表2
- ID
我想要的是删除 table2
中 ID
等于 table1
中的 subid
的任何元素,其中 table1.name
等于指定值。
如果我在 table1
ID subid name
1 ... 1 ...... name1
2 ... 3 ...... name2
3 ... 2 ...... name1
4 ... 1 ...... name2
以及 table2
ID
1
2
3
4
我想删除table2
中ID = subid的那些元素,当name = name1时,这意味着元素1和2。
类似于:
DELETE FROM table2
WHERE ID = (SELECT subid
FROM table1
WHERE NAME = "name1")
这可能吗?
你们非常亲密。
你只需要= ANY
rather than =
as the subquery can return more than one row SQL Fiddle。
DELETE
FROM table2
WHERE ID = ANY (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
虽然这更常用 IN
DELETE
FROM table2
WHERE ID IN (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
我对您发布的查询进行了一些其他更改...
- 我总是确保子查询中的列引用使用两部分名称以避免 unfortunate surprises。
- 您应该使用单引号来分隔字符串文字,以便它在默认
QUOTED_IDENTIFIER
设置下工作,并且不会被解释为引用名为name1
. 的列
您也可以使用连接删除,所以很有可能。
您可以先识别(待)删除的记录:
select t2.*
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
然后执行删除:
delete t2
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
@eckes 查看我的 fiddle 以及我用来查看它是否有效的语法:http://sqlfiddle.com/#!6/260a5