我有三张桌子:
"products" - contains products
"location" - store location
"product_orders" - joins data from products and location
SQL DUMP:
--
-- Table structure for table `location`
--
CREATE TABLE IF NOT EXISTS `location` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=77 ;
--
-- Dumping data for table `location`
--
INSERT INTO `location` (`id`, `name`) VALUES
(1, 'Miami'),
(2, 'Denver');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(255) NOT NULL DEFAULT '',
`product` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6014552 ;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `type`, `product`) VALUES
(1, 'shirt', 'red shirt'),
(2, 'shirt', 'red shirt'),
(3, 'pants', 'blue pants'),
(4, 'pants', 'blue pants');
-- --------------------------------------------------------
--
-- Table structure for table `product_orders`
--
CREATE TABLE IF NOT EXISTS `product_orders` (
`product_id` int(11) NOT NULL,
`location_id` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`product_id`,`location_id`),
KEY `ix_product_orders` (`location_id`),
KEY `ix_product_orders_1` (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product_orders`
--
INSERT INTO `product_orders` (`product_id`, `location_id`, `status`) VALUES
(1, 1, 'sold'),
(2, 2, 'sold'),
(1, 2, 'available'),
(2, 1, 'sold');
如果我想从商店'迈阿密选择所有已售出的商品 - 此查询有效:
SELECT * FROM `products`
INNER JOIN `product_orders`
ON `product_orders`.`product_id`= `products`.`id`
WHERE `product_orders`.`location_id` = '1'
AND
status = 'sold'
您如何重写以从miami商店删除所有已售出的产品?我的查询无效:
DELETE `products` FROM `products`
INNER JOIN `product_orders`
ON `product_orders`.`location_id` = `products`.`id`
WHERE `product_orders`.`location_id` = '2'
AND
status = 'sold'
答案 0 :(得分:1)
试试这个,
DELETE `products` FROM `products` INNER JOIN `products_orders`
ON `products_orders`.`location_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND
status = 'sold'
OR
DELETE prod FROM `products` AS prod INNER JOIN `products_orders`
ON `products_orders`.`location_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND
status = 'sold'
答案 1 :(得分:1)
DELETE FROM products WHERE id IN (SELECT location_id FROM products_orders WHERE location = 'miami' AND status = 'sold');
答案 2 :(得分:1)
我不确定你是如何在表中设置外键的。但是以最主要的假设来看它,产品表保存产品数据和位置保存位置数据。在您的公共表产品订单中,您有一个产品ID的产品ID的外键和按位置的位置表的另一个关系。
所以为了支持我的评论,我发布了以下查询。这是您的查询,在您的查询中更改了我认为是一个TYPO ....的字段。 :-)再次如foampile所说,我可能会保持一致......
DELETE FROM `products`
INNER JOIN `products_orders`
ON `products_orders`.`product_id` = `products`.`id`
WHERE `products_orders`.`location` = 'miami'
AND `products_orders`.status = 'sold'
;