2

我有一些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
4

2 回答 2

0

假设items2您的FROM子句中的表名是拼写错误,或者items.*是拼写错误,应该是items2.*...

您没有聚合函数 ( SUM(), COUNT(), AVG()),因此不需要GROUP BY. 您似乎也将该子句WHERE与. 第一个条件不应该存在:ONJOINWHERE

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值。LEFT JOIN

于 2012-04-24T12:55:08.747 回答
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 
于 2012-04-24T12:55:26.767 回答