我正在使用MySQL
我有一个Actions_table,它有许多用户的动作。 我还有一个Timing_table,我可以映射每个动作的时间。
我可以将Actions表中的操作与Timing表匹配,但如果没有完全匹配,我希望它使用默认时间,例如表
Actions_Table
------------------------------
| Action | No Ids |
------------------------------
|Delete ID | 5 |
|Install App1 | 1 |
|Create ID | 1 |
|Rename ID | 2 |
------------------------------
Timing_Table
-------------------
|Action |Time |
-------------------
|Delete ID | 100 |
|Install App1| 200 |
|Create ID | 50 |
|Default | 60 |
--------------------
由于没有列出"重命名ID"在Timings_Table中,我希望它使用'默认'的时间值。相反,所以我会有一些链接。
-------------------------------------
| Action | No Ids | Total Time|
-------------------------------------
|Delete ID | 5 | 500 |
|Install App1 | 1 | 200 |
|Create ID | 1 | 50 |
|Rename ID | 2 | 120 | <== value was calculated from Default
-------------------------------------
基本代码
Select a.Action, a.`No Ids`, (a.`No Ids` * b.time) as `TotalTime
From Action_Table a, Timing_Table b
Where a.Action = b.Action
然而,它不匹配任何不匹配的默认值。
答案 0 :(得分:1)
您想要的是left join
和cross join
:
Select a.Action, a.`No Ids`,
coalesce(b.time, def.time) as ImputedBTime,
(a.`No Ids` * coalesce(b.time, def.time)) as `TotalTime
From Action_Table a left join
Timing_Table b
on a.Action = b.Action cross join
(select t.* from Timing_Table t where t.action = 'default') def
简单规则:永远不要在from
子句中使用逗号。始终使用显式JOIN
语法。您应该学习不同类型的连接。