【问题标题】:How to find entities where key does not exist如何查找密钥不存在的实体
【发布时间】:2015-09-24 23:45:33
【问题描述】:

我有这个下表:

CREATE TABLE `productattributes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) DEFAULT NULL,
  `attribute_id` int(11) DEFAULT NULL,
  `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

样本数据:

id      product_id  attribute_id  value
651048  81546       132           0
651049  81546       133           1440
651050  81546       134           1440
707380  81546       136           1088

674291  84645       132           0
674292  84645       134           70560
674293  84645       133           144
674294  84645       136           2058
674295  84645       137           SS34
674296  84645       142           213
674297  84645       147           AB
674298  84645       154           F

我想知道 product_id 何时没有设置 attribute_id “136”。 从上面的示例数据中可以看出,两种产品的属性 ID“136”都设置为某个值。

如果一个产品没有这个属性,attribute_id 甚至不存在(不设置为 NULL)。 像这样:

1   5000    132 0
2   5000    133 1440
3   5000    134 1440

如何查询此表以了解哪些产品没有将attribute_id136 设置为任何值?

到目前为止我做了什么?

SELECT DISTINCT * FROM sbb.productattributes
WHERE EXISTS(attribute_id = 136) ORDER BY product_id LIMIT 100000

类似的东西。但我知道您必须在 EXIST() 语句中使用第二个 SELECT 查询。但对我来说,一切都在一张桌子内。

一个完美的结果是看到(从上面的示例数据),product_id 5000 没有 attribute_id 136 的值。我不想看到其他产品,因为它们确实有 attribute_id 136 的值。

【问题讨论】:

    标签: mysql sql database


    【解决方案1】:

    使用NOT EXISTS 排除所有attribute_id = 136 的产品:

    select *
    from productattributes p1
    where not exists (select 1 from productattributes p2
                      where p1.product_id = p2.product_id
                        and p2.attribute_id = 136)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多