我有一些mysql表:
`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 的项目,而不是至少 count > 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
但它不起作用......我可能需要If语句吗?
解决了!只需 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