【问题标题】:Query doesn't show table1 row which id is not in table2 using inner join查询不显示表 1 行,其中 id 不在表 2 中使用内连接
【发布时间】:2020-08-11 11:52:10
【问题描述】:

我有两张桌子,

table1
=======================================
pid    pname           coldate      col4
---------------------------------------
1      Tesitng Name1   2019-01-01    self
2      Tesitng Name2   2020-01-01    self
3      Tesitng Name3   2020-03-01    self2
4      Tesitng Name4   2020-04-04    self2
5      Tesitng Name5   2020-04-05    self3

table1 中的 pid 有唯一键

table2 //which have more than 600k rows
=======================================
billid   rate            pid
---------------------------------------
1        30               1
2        50               1
3        40               1
4        10               3

///在table2 billid中有唯一key

我尝试显示 table1 的所有行以及 table2 的 rate 列的总和 where table1.pid=table2.pid

结果应该是这样的

   table1
    =======================================================
    pid    pname           coldate       col4     total
    -------------------------------------------------------
    1      Tesitng Name1   2019-01-01    self      120
    2      Tesitng Name2   2020-01-01    self       0

我正在使用这个查询

    SELECT 
    t1.*
    , ttl.total
FROM table1 t1 
    inner join 
        (SELECT pid, sum(rate) as total
        FROM table2 
        GROUP BY pid) as ttl
            on ttl.pid=t1.pid
WHERE 
    t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
    AND t1.col4 = 'self' 
ORDER BY t1.pid DESC;

但它不显示表 1 中哪个 pid 不在表 2 中的行 请告诉我执行此操作的最快方法 我正在使用 php 和 mysql..

【问题讨论】:

  • “它不显示 table1 行,其中 pid 不在 table2 中”。你不问那个。你怎么期望得到那个???
  • 如果你想要table1中的行,而pid不在table2中,ttl.total有什么意义?它将永远是NULL

标签: mysql sql


【解决方案1】:

你的标题说明了一切,好像你知道你需要一个LEFT JOIN

SELECT t1.*, ttl.total
FROM table1 t1 LEFT JOIN
     (SELECT pid, sum(rate) as total
      FROM table2 
      GROUP BY pid
     ) ttl
     ON ttl.pid = t1.pid
WHERE t1.coldate BETWEEN '2020-01-01' AND '2020-04-01' AND
      t1.col4 = 'self' 
ORDER BY t1.pid DESC;

为了性能,您可能应该使用相关子查询:

SELECT t1.*,
       (SELECT SUM(tt1.rate)
        FROM table2 tt1
        WHERE ttl.pid = t1.pid
       ) total
FROM table1 t1 
WHERE t1.coldate BETWEEN '2020-01-01' AND '2020-04-01' AND
      t1.col4 = 'self' 
ORDER BY t1.pid DESC;

那么您需要在table1(col4, coldate, pid)table2(pid, rate) 上建立索引。

【讨论】:

  • 它说:错误代码:1060。重复的列名'pid'
  • 与我上面提供的查询进行比较需要很长时间
【解决方案2】:

您的子查询中已经有一个错误,您必须像下面的示例中那样删除第二个 pid。

要从 table1 获取所有行,您需要 LEFT JOIN 而不是 INNER JOIN

但无论如何,您的 Where 子句会将所有内容减少到 1 行。

    SELECT 
    t1.*
    , ttl.total
FROM table1 t1 
    LEFT join 
        (SELECT pid, sum(rate) as total
        FROM table2 
        GROUP BY pid) as ttl
            on ttl.pid=t1.pid
WHERE 
    t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
    AND t1.col4 = 'self' 
ORDER BY t1.pid DESC;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多