Mysql

三表關係順序正確但值錯誤

  • July 17, 2019

我有那些桌子

    table1
|  id  |  name  |
|  1   |  axe   |
|  2   |  bow   |
|  3   |  car   |
|  4   |  dart  |


       table2                                        table3
|  t1_id  |  number  |                        |  t1_id  |  letter  |
|  1      |  5       |                        |  1      |  a       |
|  1      |  6       |                        |  1      |  b       |
|  1      |  2       |                        |  1      |  c       |
|  2      |  2       |                        |  2      |  a       |
|  2      |  2       |                        |  2      |  c       |
|  2      |  3       |                        |  2      |  r       |
|  3      |  8       |                        |  3      |  y       |
|  3      |  3       |                        |  3      |  i       |
|  3      |  1       |                        |  3      |  a       |
|  4      |  8       |                        |  4      |  a       |
|  4      |  9       |                        |  4      |  b       |
|  4      |  10      |                        |  4      |  c       |

並且table1(id) 與 table2(t1_id)、table3(t1_id) 連結

我執行它以讓它們按最高的 letter_count匹配排序,然後按最高的 average_number匹配排序以獲得正確的結果http://www.sqlfiddle.com/#!9/69086b/8/0

SELECT 
 t1.id, 
 t1.name

FROM 
 table1 t1

INNER JOIN 
 table2 t2
   ON t2.t1_id = t1.id

LEFT JOIN 
 table3 t3
   ON t3.t1_id = t1.id
     AND t3.letter IN ('a', 'b', 'c')

GROUP BY
 t1.id

ORDER BY
 COUNT(t3.letter) DESC,
 AVG(t2.number) DESC

|  id  |  name  |
|  4   |  dart  |
|  1   |  axe   |
|  2   |  bow   |
|  3   |  car   |

一切正常


但是當我想檢查查詢是否有任何問題時,我決定檢查letter_countavg_number所以我使用了這個查詢

SELECT 
 t1.id, 
 t1.name, 
 COUNT(t3.letter) AS letter_count, 
 AVG(t2.number) AS avg_number

FROM 
 table1 t1

INNER JOIN 
 table2 t2
   ON t2.t1_id = t1.id

LEFT JOIN 
 table3 t3
   ON t3.t1_id = t1.id
     AND t3.letter IN ('a', 'b', 'c')

GROUP BY
 t1.id

ORDER BY
 letter_count DESC,
 avg_number DESC

我期望的結果是

|  id  |  name  |  letter_count  |  avg_number   |
|  4   |  dart  |  3             |  9            |
|  1   |  axe   |  3             |  4.3333333333 |
|  2   |  bow   |  2             |  2.3333333333 |
|  3   |  car   |  1             |  4            |

但我得到的結果是http://www.sqlfiddle.com/#!9/69086b/3/0

|  id  |  name  |  letter_count  |  avg_number   |
|  4   |  dart  |  9             |  9            |
|  1   |  axe   |  9             |  4.3333333333 |
|  2   |  bow   |  6             |  2.3333333333 |
|  3   |  car   |  3             |  4            |

我是否應該擔心letter_count在未來如何乘以三倍,或者這只是在我想選擇值時發生,如果我只保留它不會發生任何不好的事情ORDER BY


我只是希望它們正確排序,這是我得到的,但檢查值顯示letter_count被乘了很多次,所以我對它的性能感到困惑,或者可以忽略letter_count並且性能不會受到影響?

在多表源中很常見。中的每條記錄table3都與來自table2.

如果table3(t1_id,letter)是唯一的(按索引),那麼COUNT(DISTINCT t3.letter)將有所幫助。

如果不是,那麼唯一的解決方案是COUNT()在子查詢中table3單獨計算這個並將結果連接到table1.

引用自:https://dba.stackexchange.com/questions/243034