我有一张具有以下结构的表
Table1
itemName, codeA, codeB, codeC, codeD
Table2
purchaseDate, shopCode, itemCode
表2 itemCode是对应于商店代码的代码
例如,我有以下项目:
Table1
Item A, A1, B1, C1, D1
Item B, A2, B2, C2, D2
Table2
2012-03-27 11:00:00, 1, A1
2012-03-27 11:00:00, 2, B2
2012-03-27 13:00:00, 4, D1
在表2中,shopCode(1-4)等于表1(codeA-codeD), 如何选择table2记录和项目名称?
答案 0 :(得分:3)
SELECT
t1.itemName,
t2.purchaseDate,
t2.shopCode,
t2.itemCode
FROM
table1 t1 JOIN
table2 t2 ON t2.itemCode IN (t1.codeA, t1.codeB, t1.codeC, t1.codeD)
答案 1 :(得分:3)
SELECT t2.*, t1.itemName
from Table2 t2
INNER JOIN Table1 t1 ON
(t2.shopCode = 1 AND t2.itemCode = t1.codeA) OR
(t2.shopCode = 2 AND t2.itemCode = t1.codeB) OR
(t2.shopCode = 3 AND t2.itemCode = t1.codeC) OR
(t2.shopCode = 4 AND t2.itemCode = t1.codeD);
在这里演示 - http://sqlfiddle.com/#!2/773a4/2