简体   繁体   English

MySQL DELETE与JOIN条件

[英]MySQL DELETE with JOIN on condition

I have 3 tables; 我有3张桌子; products, variants, and stock {simplified} 产品,变体和库存{简化}

PRODUCTS id name discontinued (ENUM: 0 or 1) etc 产品ID名称已停止(ENUM:0或1)等

VARIANTS id product_id colour size VARIANTS id product_id颜色大小

STOCK id variant_id branch_id STOCK id variant_id branch_id

When the user selects to discontinue the PRODUCT I set the discontinued flag to 1. That's fine, but I want to delete the PRODUCT and VARIANTS records altogether if there is no STOCK record of the product. 当用户选择停止PRODUCT时,我将已停止的标志设置为1.这很好,但如果没有产品的STOCK记录,我想完全删除PRODUCT和VARIANTS记录。 Obviously I can do this using a SELECT query first in PHP but I would like to do it in one mySQL query. 显然,我可以首先在PHP中使用SELECT查询,但我想在一个mySQL查询中执行此操作。 This is what I have so far, but it is returning an error from mySQL: 这是我到目前为止,但它从mySQL返回一个错误:

$query = "DELETE FROM prod_lines, 
  JOIN variants ON variants.lineid = prod_lines.id
  WHERE prod_lines.id = '$lineid' AND
  (SELECT COUNT(id) FROM stock WHERE stock.variantid = variants.id) = 0";

Can anybody out there help me come up with the right solution? 有人可以帮我提出正确的解决方案吗? Maybe there is a better way that doesn't even involve a subquery? 也许有更好的方法甚至不涉及子查询?

Thanks in advance 提前致谢

I assume that the product_line table in your query is the PRODUCTS table you describe in the beginning of your post. 我假设您查询中的product_line表是您在帖子开头描述的PRODUCTS表。

DELETE prod_lines.*  -- you must specify which table you are deleting from, because there are several tables in the FROM clause
FROM prod_lines
JOIN variants ON variants.lineid = prod_lines.id
LEFT JOIN stock ON stock.variantid = variants.id
WHERE prod_lines.id = @lineid -- your "$lineid" variable here
AND stock.id IS NULL; -- selects only items with no match in the "stock" table

http://sqlfiddle.com/#!2/40a21 http://sqlfiddle.com/#!2/40a21

Try something like this,the downside is though you have to have two php variables here and also an nested query that you may not be ok with 尝试类似这样的东西,缺点是你必须在这里有两个php变量,还有一个嵌套查询你可能不太好

   DELETE FROM (select COUNT(id) countstock FROM stock s,variants v WHERE s.variantid = v.id and v.productid='$lineid') prod 
    where prod.countstock>1 and prod.productid='$lineid'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM