【问题标题】:Which is the best performance settings to perfom a triple join query哪个是执行三重连接查询的最佳性能设置
【发布时间】:2021-09-08 09:03:30
【问题描述】:

大家好,我正在做一个个人项目,但现在我几乎完成了所有工作,除了这个,我有 2 张桌子

用户

id name
1 john
2 doe

账单

id month status
1 january paid
2 february pending
3 march pending

但我试图向用户提供此信息的摘要,这将是最佳性能设置

  1. 执行三联查询 例如

    选择 u.name,a.*,b.*
    来自用户
    左加入(从 status='paid' 的账单中选择 id,max(month) as last_month_paid)a
    关于 u.id=a.id
    左加入(从 status='pending' 的账单中选择 id,min(month) as last_month_pending)b
    关于 u.id=b.id

  2. 或创建 3 个数据库视图

    a.已付帐单视图
    b.未决账单视图
    c.summary 视图

    感谢您的 cmets

【问题讨论】:

  • 视图对提高性能没有任何作用
  • 此外,没有与给定用户和账单的关联。我可以看到唯一的账单 ID,但没有给定账单 ID 的用户 ID。
  • 假设您的month 列是varchar,那么在此列上应用MAX()MIN() 是无稽之谈,因为四月总是最小值,九月总是最大值.
  • 我认为视图更省时,没有关联,因为我没有写下来,但存在于表和月份字段中它是 int

标签: mysql groupwise-maximum


【解决方案1】:

这样改写:

select  name,
        ( SELECT  max(month)
            from  bills
            where  status='paid'
              AND  id = u.id )  AS last_month_paid
        ( SELECT  min(month) as last_month_pending
            from  bills
            where  status='pending'
              AND  id = u.id )  AS last_month_pending
    from  users u

如果您需要其他列,它会变得更加复杂。看看我添加的那个标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多