簡體   English   中英

在非關系表中加入mysql中的3表

[英]join 3 table in mysql with non relation table

你好,伙計們,我有3個桌子a,桌子b,桌子c

表一

id  | name   
 1  | agent1 
 2  | agent2

表b

id  | action   
 1  | product 
 2  | saving
 3  | transfer
 4  | sell

表c

 id | table_a | table_b | status | delay(sec)
  1 |  1      | 1       | 2      | 10
  2 |  1      | 2       | 2      | 5

預期產量

name    | action  | count  |avg(delay)
 agent1 | product | 1      | 10
 agent1 | saving  | 1      | 5
 agent1 | transfer| 0      | 0
 agent1 | sell    | 0      | 0
 agent2 | product | 0      | 0
 agent2 | saving  | 0      | 0
 agent2 | transfer| 0      | 0
 agent2 | sell    | 0      | 0

誰能告訴我由於我的sql不支持outer join ,我怎么能達到預期的輸出,所以我感到困惑?

您可以使用采用如下方案INNER JOINtableAtableB無條件和LEFT JOINtableC

SELECT tableA.name, tableB.action, COUNT(tableC.id) AS `count`, AVG(delay) AS delay
FROM (tableA, tableB) LEFT JOIN tableC ON tableA.id = tableC.table_a AND tableB.id = tableC.table_b
GROUP BY tableA.name, tableB.action
ORDER BY tableA.name, tableB.action

dbfiddle.uk上的演示

SELECT a.name, b.action , COUNT(c.id) as count , AVG(delay) 
FROM test.table_a a CROSS JOIN test.table_b b 
LEFT JOIN test.table_c c
ON c.table_a = a.id AND c.table_b = b.id
GROUP BY a.id ,b.id
ORDER BY a.id,b.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM