所以我必须对数据库模式运行查询:http ://sqlfiddle.com/#!9/d0b643 ,但示例模式如下所示:
Table 1
itemID sale date salesmanID storeID
---------------------------------------------------
1 1/2015 1 1
1 3/2016 1 1
2 5/2016 2 1
2 1/2015 4 1
Table 2
itemID colorID price
--------------------------------------
1 1 23
1 2 10
1 3 13
2 1 11
2 2 14
2 3 18
Table 3
ColorID color
---------------------------------------
1 Red
2 Blue
3 Green
Table 4
SaleBegin SaleEnd ColorID salesmanID storeID
----------------------------------------------------------------
1/1/2014 12/31/2014 1 0 1
1/1/2015 12/31/2015 2 0 1
1/1/2016 12/31/2016 3 0 1
1/1/2014 12/31/2014 3 2 1
1/1/2015 12/31/2016 2 2 1
我需要在 where 子句中添加一些内容,如果有 SalesmanID 并且 Table1 中的 saleDate 介于 Table4 的 StartDate 和 Enddate 之间,请使用该颜色。否则,如果没有 salesmanID,则使用 StoreID(在本例中它们都是 1,但它们可能不同)。
我要添加的当前查询是:
select t1.itemID,t3.color,t2.price
from table_1 t1
LEFT JOIN table_2 t2
ON t1.itemID = t2.itemID
LEFT JOIN table_3 t3
ON t2.colorID = t3.colorID
LEFT JOIN table_4 t4
ON t3.colorID = t4.colorID
WHERE t1.sale_date BETWEEN saleBegin and saleEnd;
我怎么能运行这个?预期结果应如下所示:
itemID 颜色 价格
1 Blue 10
1 Green 13
2 Blue 14
2 Blue 14