我有两个MySQL表:
Table AllProducts
AccountID, ProductOwner, ProductNumber
100001, Tom, ABC1
100001, Tom, ABC2
100001, Greg, ABC3
100002, Charlie, ABC2
Table ProductData
AccountID, ProductNumber, ProductDesc
100001, ABC1, DescHere
100001, ABC2, DescHere
100001, ABC3, DescHere
100002, ABC2, DescHere
我需要删除ProductData中的所有内容,其中ProductNumbers在两个表中都相同,我将使用变量指定AccountID是什么,以及ProductOwner是谁。
E.g我知道AccountID是100001而ProductOwner是Tom。因此,我希望仅删除ProductData表中的第1行和第2行。
编辑:我相信我可能刚刚破解了我一直在努力的查询
mysql_query("DELETE ProductData.* FROM ProductData
INNER JOIN AllProducts ON ProductData.ProductNumber = AllProducts.ProductNumber
WHERE (ProductData.AccountID = '100001'
AND AllProducts.ProductOwner = 'TOM')");
我做了一个快速测试,似乎有效 - 任何想法/批评?
答案 0 :(得分:1)
自PHP 5.5.0起,您不再使用mysql_query,将来也会将其删除。您应该开始使用MySQLi或PDO_MySQL扩展程序。
我会建议你存储你的查询:
DELETE ProductData.* FROM ProductData
INNER JOIN AllProducts ON ProductData.ProductNumber = AllProducts.ProductNumber
WHERE (ProductData.AccountID = '100001'
AND AllProducts.ProductOwner = 'TOM'
在数据库的存储过程中。
例如,当使用PDO时,您可以按如下方式调用它:
$db = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
// Be sure to cleanse the passed in arguments!
$stmt = $db->prepare("CALL deleteProductData($accountId, $productOwner)");
// call the stored procedure
$stmt->execute();
存储过程示例:
CREATE DEFINER=`root`@`localhost` PROCEDURE `deleteProductData`(IN `accountId` BIGINT, IN `productOwner` VARCHAR(128))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DELETE FROM ProductData
INNER JOIN AllProducts ON ProductData.ProductNumber = AllProducts.ProductNumber
WHERE ProductData.AccountID = accountId AND AllProducts.ProductOwner = productOwner;
END
通过这种方式,您可以将所有MySQL代码移出php并进入它所属的数据库。
答案 1 :(得分:0)
DELETE FROM ProductData
WHERE ProductNumber IN
(SELECT ProductNumber
FROM AllProducts
WHERE AccountId=100001
AND ProductOwner='Tom')