【问题标题】:given two tables and a third table relating the two, select only the rows from table A that match a list of table B rows, but don't match another list给定两个表和与这两个表相关的第三个表,仅选择表 A 中与表 B 行列表匹配的行,但不匹配另一个列表
【发布时间】:2020-10-07 14:09:16
【问题描述】:

我的测试架构、数据和查询:https://www.db-fiddle.com/f/apQXP7MGfDKPHVw6ucmuNv/1

我的查询应该只选择与所有 IN () 部分特征匹配的汽车,而不是与 NOT IN () 匹配的汽车,并且它应该只选择每辆匹配的汽车一次。

在我的示例数据中,当我运行查询时,我希望看到一行包含两列,其中包含与 where 子句的 IN () 部分中的特征列表匹配的唯一汽车的 ID 和名称不匹配 where 子句的 NOT IN () 部分中的特征列表:

1 | camry

相反,每当汽车与 where 子句的 IN () 部分中的某个值匹配时,我都会得到一行包含汽车名称的行:

1 | camry    | 2 | 1 | 2 | 2 | backup camera
1 | camry    | 3 | 1 | 3 | 3 | sun roof
2 | forester | 4 | 2 | 2 | 2 | backup camera
2 | forester | 5 | 2 | 3 | 3 | sun roof

【问题讨论】:

    标签: mysql sql database join rdbms


    【解决方案1】:

    如果您希望每辆车有一排,则需要聚合。我想你想要的是:

    SELECT c.id, c.name
    FROM `car` c JOIN
         `bridge_car_features` cf  
          ON car.id = bridge.car_id JOIn
          `features` f  
          ON cf.features_id = f.id 
    GROUP BY c.id
    HAVING SUM(f.name IN ('backup camera', 'sun roof')) > 0 AND  -- has at least one of these
           SUM(f.name IN ('four wheel drive')) = 0;              -- has none of these
    

    这是fiddle

    注意:为了让小提琴正常工作,我将id 设置为cars 的主键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多