如果存在,则连接两个表以替换第2个表中的新值

时间:2016-01-29 05:15:52

标签: mysql sql database join

我有两张像belew的桌子

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

我想从表1中获取数据但是如果Table2中的记录反映到Table1 CId,那么Table2的价格将替换为Table1的价格。

例如我的UserId是1,如果我通过提到的senario得到数据,则MId为1我应该得到结果;

1       A      100  
2       B      200
3       C      120   

3 个答案:

答案 0 :(得分:2)

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);

答案 1 :(得分:1)

您可以在left join旁边查看第二个表格中的null值。如果第二个价格为null,则使用first table's price

SELECT t1.CId, t1.name 
CASE WHEN t2.price IS NULL 
THEN t1.price 
ELSE t2.price END AS Price 
FROM table1 t1 
LEFT JOIN table2 t2 
ON t1.CId = t2.CId 
WHERE WHERE t1.MId = 1 
AND (t2.UserId = 1 OR t2.UserId IS NULL);

试试这个希望这会奏效。

答案 2 :(得分:0)

CREATE TABLE table1(
    [cid] [int] NULL,
    [Name] [nvarchar](50) NULL,
    [price] [bigint] NULL,
    [MID] [int] NULL
)

CREATE TABLE [table2](
    [id] [int] NULL,
    [userid] [int] NULL,
    [CId] [int] NULL,
    [price] [bigint] NULL
)

GO
INSERT [dbo].[table1] ([cid], [Name], [price], [MID]) VALUES (1, N'A', 100, 1)
GO
INSERT [dbo].[table1] ([cid], [Name], [price], [MID]) VALUES (2, N'B', 110, 1)
GO
INSERT [dbo].[table1] ([cid], [Name], [price], [MID]) VALUES (3, N'C', 120, 1)
GO
INSERT [dbo].[table1] ([cid], [Name], [price], [MID]) VALUES (4, N'D', 120, 2)
GO
INSERT [dbo].[table2] ([id], [userid], [CId], [price]) VALUES (1, 1, 2, 200)
GO
INSERT [dbo].[table2] ([id], [userid], [CId], [price]) VALUES (1, 2, 2, 200)
GO


and  Query-----------------------------------

SELECT        t1.cid, t1.Name,
              case when t1.cid=t2.cid then t2.price else t1.price end as Price
FROM          table1  t1
INNER JOIN  table2 t2 ON t1.MID = t2.userid
where t2.userid=1