我目前正在尝试从两个表中获取值。我有表A和表B
表A包含我将用于显示结果的主要数据。
如果满足表A中的某个条件,表B保存保存数据的数据。
表A
UserID |Date |useExternalInfo |Address |Hours
1 |12/12/2014 |0 |myaddress 1 | 4
2 |13/12/2014 |0 |myaddress 2 | 9
3 | 14/12/2014 |1 | myaddress 3| 12
表B
ID | Date |Hours
1 | 12/12/2014 | 10
2 | 13/12/2014 | 6
3 | 14/12/2014 | 7
3 | 15/12/2014 | 8
我想要的查询是
select UserID, Date, (hours from TableA if UseExternalinfo is 0, and from hours TableB if useextername)
from TableA
where
TableA.Date = '14/12/2014' if (ExternalUse = 0) or TableB.Date = '14/12/2014' if (ExternalUse = 1)
and user = 3
例如,如果date是'14 / 12/2014'且user = 3,我需要找到7而不是12的小时,因为use external是1。
不确定这是否有意义我只是基本上试图获得'where if'语句,如果存在这样的事情。有人能指出我正确的方向,我能做到这一点。
感谢
答案 0 :(得分:1)
select UserID,
Date,
case when UseExternalInfo = 1 then tableA.hours else tableB.hours end
from TableA left join tableB on TableA.UserId = tableB.Id
where TableA.Date = '14/12/2014' and
TableB.Date = '14/12/2014' and
user = 3