使用内部联接删除一行数据[重复]
Posted
技术标签:
【中文标题】使用内部联接删除一行数据[重复]【英文标题】:Deleting a row of data using inner joins [duplicate] 【发布时间】:2018-10-05 04:26:53 【问题描述】:我正在尝试使用内部联接从我的表中删除一行数据,但是我的代码似乎无法正常工作。我首先写了一个 Select 语句来确保我选择了正确的数据:
SELECT * FROM tblPlaylist_Tracks
INNER JOIN tblPlaylist ON tblPlaylist_Tracks.PlaylistID = tblPlaylist.PlaylistID
INNER JOIN tblTrack ON tblPlaylist_Tracks.TrackID = tblTrack.TrackID
WHERE Playlist_Name = "x" AND Track_Name = "y";
然后我将 select 替换为 delete 语句,但这在第 2 行引发了错误:
DELETE FROM tblPlaylist_Tracks
INNER JOIN tblPlaylist ON tblPlaylist_Tracks.PlaylistID = tblPlaylist.PlaylistID
INNER JOIN tblTrack ON tblPlaylist_Tracks.TrackID = tblTrack.TrackID
WHERE Playlist_Name = "x" AND Track_Name = "y";
我试图在 Delete From 语句之间指定要删除的内容,但这似乎不起作用,因为查询不再将 DELETE 识别为命令 感谢任何可能的帮助。非常感谢
【问题讨论】:
您有什么理由不向我们显示错误消息? 【参考方案1】:这是有道理的 - SQL 会将您的请求解释为从三个表中删除,或者从您的联接构建的“虚拟”表中删除。
我会尝试将您的工作选择包装到删除中:
delete from tblPlaylist_Tracks
where primaryKey not in (
SELECT primaryKey FROM tblPlaylist_Tracks
INNER JOIN tblPlaylist ON tblPlaylist_Tracks.PlaylistID =
tblPlaylist.PlaylistID
INNER JOIN tblTrack ON tblPlaylist_Tracks.TrackID = tblTrack.TrackID
WHERE Playlist_Name = "x" AND Track_Name = "y";
)
当然,“primaryKey”是 tblPlaylist_Tracks 的唯一标识符
【讨论】:
谢谢,这是有道理的,但是我收到了这个错误:“#1093 - 您不能在 FROM 子句中指定目标表 'tblPlaylist_Tracks' 进行更新” 有点 Google-fu 和 ... ***.com/questions/45494/…【参考方案2】:我会这样写:
DELETE pt
FROM tblPlaylist_Tracks pt INNER JOIN
tblPlaylist p
ON pt.PlaylistID = p.PlaylistID INNER JOIN
tblTrack t
ON pt.TrackID = t.TrackID
WHERE p.Playlist_Name = 'x' AND t.Track_Name = 'y';
这对你有用吗?
我不确定您所说的“不再将 DELETE
识别为命令”是什么意思。将DELETE
与JOIN
一起使用时,您需要在FROM
之前使用表别名(或表名)。
【讨论】:
以上是关于使用内部联接删除一行数据[重复]的主要内容,如果未能解决你的问题,请参考以下文章