mysql - 连接两个表以替换第二个表中的新值(如果存在)

标签 mysql sql database join

我有两个如下表

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   

最佳答案

SQL FIDDLE

试试这个

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/

相关文章:

php - 如何编写主表和副表的 SQL 多插入查询

sql - 将列名作为参数传递时,查询显示不正确的输出

mysql - 如何查看MySql用户的创建时间?

mysql - 当我尝试计算喜欢的数量时,它会显示食谱中使用的成分数量

php - Mysql表连接2个表

sql - 尝试通过Spark Streaming运行SparkSQL

php - MySQL 存储过程返回 0 行

Mysql数据截断: Data truncation: Out of range value for column 'agentID' at row 4

sql - 这种订单情况应该如何设置数据库表

javascript - 谷歌图表 mysql PHP