我有这张表(A):
ID PROD PER
1 45 1
2 21 2
3 45 3
4 223 12
5 543 6
表B:
ID CAS DATE
1 ttt 062017
2 ddd 062017
3 fff 062017
4 fre 062017
5 grs 062017
条件:
PER = 1 and DATE between 01%%%% and 12%%%%
PER = 2 and DATE=02%%%% OR DATE=04%%%% OR DATE=06%%%% OR DATE=08%%%% OR DATE=10%%%% OR DATE=12%%%%
PER = 3 and DATE=03%%%% OR DATE=06%%%% OR DATE=09%%%% OR DATE=12%%%%
PER = 4 and DATE=04%%%% OR DATE=08%%%% OR DATE=12%%%%
PER = 6 and DATE=06%%%% OR DATE=12%%%%
PER = 12 and DATE=12%%%%
我想加入A和B:
select * from A
join B
on A.ID=B.ID
CONDITIONS
预期结果:
ID PROD CAS PER DATE
1 45 ttt 1 062017
2 21 ddd 2 062017
3 45 fff 3 062017
5 543 grs 6 062017
我希望我已经正确解释了。简而言之,我正在寻找的是具有暴露条件的表之间的连接。
答案 0 :(得分:0)
SELECT *
FROM A
JOIN B ON
A.ID = B.ID
WHERE
(PER = 1 and (DATE between 01%%%% OR 12%%%%)) OR
(PER = 2 and (DATE=02%%%% OR DATE=04%%%% OR DATE=06%%%% OR DATE=08%%%% OR DATE=10%%%% OR DATE=12%%%%)) OR
(PER = 3 and (DATE=03%%%% OR DATE=06%%%% OR DATE=09%%%% OR DATE=12%%%%)) OR
(PER = 4 and (DATE=04%%%% OR DATE=08%%%% OR DATE=12%%%%)) OR
(PER = 12 and DATE=12%%%%)
有关详细信息,请访问:https://www.w3schools.com/sql/sql_where.asp
答案 1 :(得分:0)
试试这个(对于mysql):
select a.*, b.cas, b.`date`
from tablea a
join tableb b
on a.id = b.id
and mod(left(b.`date`, 2) + 0, a.per) = 0
rextester中的Demo。
答案 2 :(得分:0)
您可以使用以下查询
select A.ID,A.PROD,D.CAS,A.PER,B.DATE from A
join B
on A.ID=B.ID
WHERE
(A.PER = 1 and B.DATE between 01%%%% and 12%%%%) AND
(A.PER = 2 and B.DATE=02%%%% OR B.DATE=04%%%% OR B.DATE=06%%%% OR B.DATE=08%%%% OR B.DATE=10%%%% OR B.DATE=12%%%%) AND
(A.PER = 3 and B.DATE=03%%%% OR B.DATE=06%%%% OR B.DATE=09%%%% OR B.DATE=12%%%%) AND
(A.PER = 4 and B.DATE=04%%%% OR B.DATE=08%%%% OR B.DATE=12%%%%) OR
(A.PER = 12 and B.DATE=12%%%%)
如有任何问题,请告诉我
答案 3 :(得分:0)
您应该使用LIKE
关键字进行比较。见下文:
SELECT tab1.id,
tab1.PROD,
tab2.CAS,
tab2.Datum
FROM Table1 tab1
INNER JOIN Table2 tab2 ON tab1.ID = tab2.ID
WHERE (tab1.PER = 1 AND tab2.DATUM BETWEEN '01%' AND '12%')
OR (tab1.PER = 2 AND (tab2.DATUM LIKE '02%' OR tab2.DATUM LIKE '04%' OR tab2.DATUM LIKE '06%' OR tab2.DATUM LIKE '08%' OR tab2.DATUM LIKE '10%' OR tab2.DATUM LIKE '12%'))
OR (tab1.PER = 3 AND (tab2.DATUM LIKE '03%' OR tab2.DATUM LIKE '06%' OR tab2.DATUM LIKE '09%' OR tab2.DATUM LIKE '12%'))
OR (tab1.PER = 4 AND (tab2.DATUM LIKE '04%' OR tab2.DATUM LIKE '08%' OR tab2.DATUM LIKE '12%'))
OR (tab1.PER = 12 AND tab2.DATUM = '12%')
这是一个简单的解决方案,应该适用于所有主要的DBMS。
你可以在这里看到这个 - > http://rextester.com/MYBHC51508
希望这有帮助!!!