我必须在我的桌子上显示完全缺货产品。这里1号是库存,2号是缺货。在这里,我只需要获取product_id的缺货(2),如果有任何product_id,至少有一行有库存(1),它会认为是库存,否则认为是缺货。
请在此处查看,我已尝试此查询,但结果未按预期进行
答案 0 :(得分:2)
我不明白100%的问题, 也许这可以帮到你。
这是指向SQLfiddle http://sqlfiddle.com/#!9/75509d/12/0
的链接SELECT p1.*
FROM price p1
LEFT JOIN price p2
ON p1.product_id = p2.product_id
AND p2.stockstatus = 1
WHERE p1.stockstatus = 2
AND p2.stockstatus IS NULL
ORDER BY p1.product_id ASC
答案 1 :(得分:0)
出局股票应
SELECT *
FROM `price`
WHERE product_id not in (
select product_id from `price` where stockstatus ='1')
ORDER BY `product_id` ASC
答案 2 :(得分:0)
我认为这应该足够了
select * from price where product_id NOT IN (select product_id from price where stockstatus = 1)
表名中也不需要撇号。 (如果您计划添加更多stockstatuses,请考虑在子查询后添加AND stockstatus = 2
答案 3 :(得分:0)
/*CREATE TABLE IF NOT EXISTS `price` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`price` int(11) NOT NULL,
`stockstatus` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=innodb DEFAULT CHARSET=latin1;
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(1, '100', 1000, '1');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(2, '100', 500, '1');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(3, '100', 800, '2');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(4, '100', 700, '1');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(5, '101', 700, '2');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(6, '101', 699, '2');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(7, '102', 700, '1');
INSERT INTO `price` (`id`, `product_id`, `price`, `stockstatus`) VALUES
(8, '102', 699, '1');
*/
select s.product_id, s.instock,
case
when s.instock = 0 then 'Out of stock'
else 'In Stock'
end as 'Status'
from
(
select product_id,
max(case when stockstatus = 1 then 1 else 0 end) as instock
from price
group by product_id
) s
where s.instock = 0
;