我有两个如下表
Table1:
CId -- Name -- Price -- MId
1 A 100 -- 1
2 B 110 -- 1
3 C 120 -- 1
4 D 120 -- 2
Table2:
Id -- UserId -- CId -- Price
1 1 2 200
1 2 2 200
我想从表一获取数据,但是如果表2中有一条记录引用了表1的CId,那么表2的价格将替换为表1的价格。
例如,我的 UserId 是 1 并且 MId 是 1,如果我通过提到的 senario 获取数据,我应该得到结果;
1 A 100
2 B 200
3 C 120
最佳答案
试试这个
select t1.cid,t1.name,
case when t2.cid is null
then t1.price
else t2.price
end as Price
from table1 t1 left join table2 t2 on t1.cid =t2.cid
where t1.mid =1 AND (t2.UserId = 1 OR t2.UserId IS NULL);
关于mysql - 连接两个表以替换第二个表中的新值(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077372/