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

时间:2019-01-30 08:39:12

标签: mysql database

你好,我有3个表a,表b,表c

表a

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,所以我怎么能达到预期的输出?

2 个答案:

答案 0 :(得分:2)

您可以使用以下解决方案,其中INNER JOINtableA上的tableB无条件,而LEFT JOIN上的tableC

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
  

demo on dbfiddle.uk

答案 1 :(得分:2)

Option Explicit 

Dim startTime, endTime

    ' Using time literals
    If InTime( #10:05#, #20:30# ) Then 
        WScript.Echo "In time range"
    Else
        WScript.Echo "NOT in time range"
    End If 

    ' Using strings
    If InTime( CDate("10:05") , CDate("20:30") ) Then 
        WScript.Echo "In time range"
    Else
        WScript.Echo "NOT in time range"
    End If 

    ' Check over midnight
    If InTime( #20:30# , #10:05# ) Then 
        WScript.Echo "In time range"
    Else
        WScript.Echo "NOT in time range"
    End If 

' Logic moved to a function to avoid duplication in previous samples 
Function InTime( startTime, endTime )
Dim currentTime
    currentTime = Time()

    If startTime <= endTime Then 
        ' If startTime <= endTime both are in same day 
        '   current time should be 
        '       greater than startTime 
        '       AND lower than endTime
        '
        '                        >----------------------------<
        '  0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.
        '
        InTime = CBool( ( currentTime >= startTime ) And ( currentTime <= endTime ) )
    Else 
        ' startTime > endTime when both times don't belong to same day
        '   current time should be 
        '       greater than start time (towards midnight) 
        '       OR lower than end time (backwards to midnight)
        '
        '                         >---------|--------------------<
        '  13.14.15.16.17.18.19.20.21.22.23.0.1.2.3.4.5.6.7.8.9.10.11.12.
        '
        '  ----------------------<                             >---------
        '  0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.
        '
        InTime = CBool( ( currentTime >= startTime ) Or ( currentTime <= endTime ) )
    End If 
End Function