2012-04-24 69 views
2

我有一些MySQL表:Mysql的选择,如果只有所有大小等于0

`items` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `cat_id_p` int(11) NOT NULL, 
    `cat_id` int(11) DEFAULT NULL, 
    `brand_id` int(11) DEFAULT NULL, 
... 
) 

`items_sizes` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `item_id` int(11) NOT NULL, 
    `size_id` int(11) NOT NULL, 
    `count` int(11) DEFAULT '1', 
... 
) 

,我需要选择其中只有items_sizes.count < 1,而不是项目具有项目至少计数> 1

这里是SQL查询:

SELECT 
    DISTINCT `items`.* 
FROM 
    (`items2`) 
    LEFT JOIN `items_sizes` ON items_sizes`.`item_id` = `items`.`id` 
WHERE ... 
    AND `items_sizes`.`item_id` = items.id 
    AND `items_sizes`.`count` < 1 
GROUP BY `items`.`id` 
ORDER BY `items`.`id` desc 
LIMIT 30 

但它不工作...可能是我需要的,如果声明?


已解决!只需用SUM和HAVING

SELECT DISTINCT `items`.*, sum(items_sizes.count) 
FROM (`items`) 
LEFT JOIN `items_sizes` ON `items_sizes`.`item_id` = `items`.`id` 
WHERE ... 
GROUP BY `items`.`id` 
having sum(items_sizes.count)=0 
ORDER BY `items`.`id` desc LIMIT 30 

回答

0

FROM条款假设表名items2是一个错字或items.*是笔误,应该是items2.* ...

你没有聚合函数(SUM(), COUNT(), AVG()),所以不需要GROUP BY。它似乎也混合了WHERE从句与JOIN中使用的ON从句。第一WHERE条件不应该存在:

SELECT 
    DISTINCT items2.* 
FROM 
    items2 
    LEFT JOIN items_sizes ON items2.id = items_sizes.item_id 
WHERE ... 
    AND items_sizes.count < 1 
ORDER BY items2.id desc 
LIMIT 30 

请注意,您WHERE条款,我们没有看到(WHERE ...)的部分可能是显著这里还有...

LEFT JOIN可能不必要的,并且可以仅仅是JOIN,因为items_sizes.count < 1将消除将返回的NULL值。

+0

items2 - 是的,对不起 – mindsupport 2012-04-24 13:29:38

+0

@mindsupport好了,一切都改变为'items2'以上。 – 2012-04-24 13:32:24

0
SELECT 
    DISTINCT * 
FROM 
    `items` 
WHERE 
    NOT EXISTS (
    SELECT * FROM `items_sizes` 
    WHERE 
      `items_sizes`.`item_id` = `items`.`id` 
     AND `items_sizes`.`count` > 0 
) 
    -- ... 
ORDER BY `id` desc 
LIMIT 30 
相关问题