【问题标题】:sql table design to fetch records with multiple inclusion and exclusion conditionssql表设计以获取具有多个包含和排除条件的记录
【发布时间】:2017-07-13 12:26:54
【问题描述】:

我们希望根据以下参数选择客户,即客户应该在:

  1. 特定城市,即 cityId=1,2,3...

  2. 应排除特定的 customerId,即 customerId=33,2323,34534...

  3. 具体年龄,即 5 岁、7 岁、72 岁...

此包含和排除列表可以很长。

我们应该如何为此设计数据库:

  1. 为这些包容性城市创建单独的表“customerInclusionCities”并执行以下操作:

从 cityId 所在的客户中选择 *(从 customerInclusionCities 中选择 cityId)

我们为年龄做一些,创建表“customerEligibleAge”,其中包含符合条件的年龄条目的所有条目:

select * from customers where age in (select age from customerEligibleAge)

并为排除客户创建单独的表“customerIdToBeExcluded”:

select * from customers where customerId not in (select customerId from customerIdToBeExcluded)

  1. 创建一个包含类别和 ID 的表。 即 Category1 表示城市,Category2 表示要排除的 CustomerIds。

哪种方法更好,为这些参数创建一个表,还是为每个列表(即年龄、客户 ID、城市)创建单独的表?

【问题讨论】:

  • 您是否探索过构建星型模式?

标签: mysql sql database-design


【解决方案1】:

IN ( SELECT ... ) 可能非常慢。将查询作为单个 SELECT 进行,不包含子查询。我假设所有 3 列都在同一个表中? (如果不是,那会增加复杂性。)WHERE 子句可能有 3 个 IN ( constants ) 子句:

SELECT ...
    FROM tbl
    WHERE cityId IN (1,2,3...)
      AND customerId NOT IN (33,2323,34534...)
      AND age IN (5, 7, 72)

拥有(至少):

INDEX(cityId),
INDEX(age)

(被否定的东西不太可能使用索引。)

查询将使用其中一个索引;两者兼有将为优化器提供它认为更好的选择。

或者...

SELECT c.*
    FROM customers AS c
    JOIN cityEligible AS b  ON b.city = c.city
    JOIN customerEligibleAge AS ce  ON c.age = ce.age
    LEFT JOIN customerIdToBeExcluded AS ex ON c.customerId = ex.customerId
    WHERE ex.customerId IS NULL

建议的索引(可能为PRIMARY KEY):

customers: (city)
customerEligibleAge: (age)
customerIdToBeExcluded: (customerId)

为了进一步讨论,请为每个表提供SHOW CREATE TABLE,为任何实际有效的查询提供EXPLAIN SELECT ...

【讨论】:

  • 我忘了提到我们希望这个 cityIds、customerIds、age 列表是可配置的,因此我们会将它们保存在表格中,而不是直接在 SP 中写入。
  • 您的客户端语言是什么?
  • 我们正在使用mysql
  • PHP?爪哇?没有代码?如果没有代码,那么一长串 customerID 是从哪里来的?
  • 调用这个SP的是C#。
【解决方案2】:

如果你只使用数据库那个操作,我推荐使用第一种解决方案。此外,第一个解决方案的部署非常简单。

第二个解决方案填满了垃圾数据库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多