douke1954 2018-06-01 08:40
浏览 73
已采纳

如何在一个删除查询中使用多个表名 - 并非所有表都有数据

What I need

I have a database called dbtuts and it has total 7 tables.

Table names are tbl_uploads, variationtable1, variationtable2, variationtable3, variationtable4, variationtable5, variationtable6.

All these tables have a column called prjId.

I want to delete a row from tbl_uploads table and from variationtable1 to variationtable6 whereby prjId is lets say xxxx .

But the problem is variationtable1 to variationtable6 may or may not have this xxxx data for prjId column.

Is there any way whereby I can execute a single query that will delete xxxx if there is such a data.

My Codes

I tried to do the following way, but it is not working.

$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);

Does anyone have some idea?

  • 写回答

2条回答 默认 最新

  • dsjzmrz78089 2018-06-01 08:51
    关注

    You can do it with a single query using 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'
    

    Demo here

    Note: This kind of query wouldn't be necessary if your database schema was properly designed. The correct way to implement this kind of funcionality is to create foreign keys in each of the dbtuts.variationtablex tables with ON CASCADE DELETE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line