如果所有大小都等于 0,则 Mysql 选择

标签 mysql

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

最佳答案

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 

关于如果所有大小都等于 0,则 Mysql 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298175/

相关文章:

php - 在 mysql_query 中使用 mysql_insert_id

java - B 类构造函数的参数 0 需要 A 类类型的 bean,但无法找到

java - 使用 JpaRepository 同时保存组合对象

mysql - innodb_system 数据文件 'ibdata1' 必须是可写的 - 用户 root@localhost 的访问被拒绝

mysql - NodeJS - 如何将 mysql 连接从主进程传递到子进程?

php - 拉维尔 5 : how can I retrieve and display all posts that belong to certain category

python mysqldb 打印文本,即使代码中没有打印语句

将 CASE WHEN 与另一个 CASE WHEN 结合使用的 MySQL 解决方案

java - 解析文本行并添加到 MySQL

mysql insert on duplicate key related deadlock