【问题标题】:Adding WHERE clause of third table in MySQL whose ID is present in first two Inner joined tables在 MySQL 中添加第三个表的 WHERE 子句,其 ID 存在于前两个内连接表中
【发布时间】:2019-01-19 10:03:28
【问题描述】:

我有以下查询,其中两个表的计数被划分并显示更多其他列值。

这两个表都是通过月/年连接的。

  select 
        (a.count_one / b.count_two) as final_count, a.orders,
        a.Months, b.Sum
    from 
        (
            select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders 
            from first_table
            GROUP BY Months)
        ) a
    INNER JOIN
        (
            select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
            from second_table
            GROUP BY Months)
        ) b
    ON a.Months = b.Months

输出:

**Month and Year**    **Final_Count**
January 2016              126
February 2016             123
March 2016                 45
....                      ....
...                       ....
...                       ....

What is required?

存在第三个表,其键在 first_Table 和 second_table 中。我需要放一个WHERE子句,基于第三张表,即WHERE thirdtable.name='Any name'

因此,无论出现与 thirdtable.name 相关的 ID,这些结果都应该显示,但我无法实现。

我尝试了什么?

我尝试了第三个 INNER join AS:

INNER JOIN third_table ON a.shid= third_table.id WHERE thirdtable.name='Any name'

但是,在这种情况下不会显示任何结果。

有什么建议吗?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    子查询不选择 id 列,因此没有可比较的 a.shid。而且由于子查询是按月份分组的,所以不能选择其中的id列。

    您需要加入子查询中的第三个表。

    select 
        (a.count_one / b.count_two) as final_count, a.orders,
        a.Months, b.Sum
    from 
        (
            select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders 
            from first_table
            JOIN third_table ON first_table.shid = third_table.id
            WHERE third_table.name = 'Any name'
            GROUP BY Months)
        ) a
    INNER JOIN
        (
            select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
            from second_table
            JOIN third_table ON second_table.shid = third_table.id
            WHERE third_table.name = 'Any name'
            GROUP BY Months)
        ) b
    ON a.Months = b.Months
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多