简体   繁体   English

条件UPDATE sqlite语句

[英]conditional UPDATE sqlite statement

I am working on sqlite 1st time 我第一次在sqlite上工作
I have need help on following problem 我需要以下问题的帮助
I have 2 tables as follows 我有2张桌子,如下

test1 TEST1


key value 核心价值
a 1 1
b 2 b 2
c 3 c 3
e 7 e 7
f 41 f 41
j 52 第52章

test2 TEST2


key value 核心价值
a null 空值
b null b null
c null c null
d null d空
e null e空
f null f null
g null g null
j null j null

I am trying to updating values of test2 if key in table test2 = test1 then update value or else put null 我正在尝试更新test2的值,如果表test2中的键= test1然后更新值,否则将其设置为null

expected output is like this 预期的输出是这样的

test2 TEST2


key value 核心价值
a 1 1
b 2 b 2
c 3 c 3
d null d空
e 7 e 7
f 41 f 41
g null g null
j 52 第52章

I try this query 我尝试这个查询

insert into test2([value]) select test1.value 插入test2([value])选择test1.value
from test1, test2 从test1,test2
where test2.value= test1.value; 其中test2.value = test1.value;

but it not working 但它不起作用
how to solve this? 如何解决呢?

(Assuming you mean conditional UPDATE, not INSERT) (假设您的意思是条件UPDATE,而不是INSERT)

Fortuitously, it seems you need to reset test2 to null where the join fails, so you can do an update with the set specified as a subquery: 幸运的是,似乎需要在连接失败的地方将test2重置为null,因此可以使用指定为子查询的集合进行更新:

update test2
set value = 
(SELECT t1.value
 FROM test1 t1 where t1.key = test2.key
 LIMIT 1);

SqlFiddle: SqlFiddle:

The LIMIT will ensure just one row returned, but if the relationship between test1 and test2 isn't 1:1 you will need to apply logic to determine how to join the two tables. LIMIT将确保仅返回一行,但是如果test1和test2之间的关系不是1:1,则需要应用逻辑以确定如何联接两个表。

Try this, not know sqllite syntax but should be like this. 试试这个,不知道sqllite语法,但是应该像这样。 Because your test2 table already have null value so only you have to update value column where key value matched with test1 table 因为您的test2表已经具有空值,所以只需要更新键值与test1表匹配的value列

MSSQL:- MSSQL: -

UPDATE R 
SET R.[value] = p.[value]
FROM dbo.test2 AS R
INNER JOIN dbo.test1 AS P 
       ON R.[key] = P.[key] 

I just follow this then I see that sql lite does not support join in update statement, but you can use in sub query 我只是按照此操作,然后看到sql lite不支持在update语句中加入,但可以在子查询中使用

SQLLITE SQLLITE

UPDATE test2 SET [value] = ( 
             SELECT [value] FROM test1 WHERE test1.key = test2.key)

Try this 尝试这个

UPDATE test2 SET value = (SELECT test1.value FROM test1 WHERE test2.key =test1.key) ; 更新test2 SET值=(从test1那里选择test1.value,在test2.key = test1.key处);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM