我需要什么
我有一个名为dbtuts的数据库,它共有7个表。
表名是tbl_uploads,variationtable1,variationtable2,variationtable3,variationtable4,variationtable5,variationtable6。
所有这些表都有一个名为prjId
的列。
我想从tbl_uploads表中删除一行,并从variationtable1删除到variationtable6,其中prjId可以说是xxxx。
但问题是变化可变1到变化表6可能有也可能没有prjId列的xxxx数据。
有没有办法可以执行单个查询,如果有这样的数据就会删除xxxx。
我的代码
我尝试按以下方式操作,但它无效。
$deleteQuery = "
DELETE
FROM dbtuts.tbl_uploads
, dbtuts.variationtable1
, dbtuts.variationtable2
, dbtuts.variationtable3
, dbtuts.variationtable4
, dbtuts.variationtable5
, dbtuts.variationtable6
WHERE prjId = 'xxxx'
";
$resultDeleteQuery = mysqli_query($conn,$deleteQuery);
有没有人有想法?
答案 0 :(得分:2)
您可以使用LEFT JOIN
进行单个查询:
DELETE t, v1, v2, v3, v4, v5, v6
FROM dbtuts.tbl_uploads t
LEFT JOIN dbtuts.variationtable1 v1 ON t.prjId = v1.prjId
LEFT JOIN dbtuts.variationtable2 v2 ON t.prjId = v2.prjId
LEFT JOIN dbtuts.variationtable3 v3 ON t.prjId = v3.prjId
LEFT JOIN dbtuts.variationtable4 v4 ON t.prjId = v4.prjId
LEFT JOIN dbtuts.variationtable5 v5 ON t.prjId = v5.prjId
LEFT JOIN dbtuts.variationtable6 v6 ON t.prjId = v6.prjId
WHERE t.prjId = 'xxxx'
注意:如果您的数据库架构设计得当,那么这种查询就不是必需的。实现这种功能的正确方法是使用dbtuts.variationtablex
在每个ON CASCADE DELETE
表中创建外键。
答案 1 :(得分:1)
这将是最简单的方法,并在1个查询中
$deleteQuery = "DELETE FROM dbtuts.tbl_uploads WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable1 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable2 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable3 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable4 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable5 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable6 WHERE prjId = 'xxxx'";
请记住在执行此查询时使用预准备语句,以防止您的项目遭到SQL注入 - 感谢Strawberry提及 你可以这样做
$stmt = $mysqli->prepare("DELETE FROM dbtuts.tbl_uploads WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable1 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable2 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable3 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable4 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable5 WHERE prjId = 'xxxx';
DELETE FROM dbtuts.variationtable6 WHERE prjId = 'xxxx'";);
$stmt->execute();
$stmt->close();