简体   繁体   English

mysql根据不同条件更新不同的列

[英]mysql update different columns based on different conditions

I have this simple table: 我有这个简单的表:

list1 (VARCHAR), list2 (VARCHAR), list3 (VARCHAR), list1cnt (INT), list2cnt (INT), list3cnt (INT)

Now I want to use one single mysql query to see which of the lists have the word 'book' inside, and update the proper 'cnt' columns accordingly. 现在,我想使用一个单一的mysql查询来查看其中的哪些列表中包含单词“ book”,并相应地更新适当的“ cnt”列。

So if list1 has the word 'book' inside, increment list1cnt value; 因此,如果list1中包含单词'book',则递增list1cnt的值;

if list2 has the word 'book' inside, increment list2cnt value; 如果list2里面有单词'book',则递增list2cnt的值;

if list3 has the word 'book' inside, increment list3cnt value; 如果list3里面有单词'book',则递增list3cnt的值;

So far my query is this (as you can see, I am running 3 separate queries). 到目前为止,我的查询是这样(如您所见,我正在运行3个单独的查询)。

mysqli_query($link,"UPDATE table SET list1cnt+='1' WHERE list1 LIKE '%book%'");
mysqli_query($link,"UPDATE table SET list2cnt+='1' WHERE list2 LIKE '%book%'");
mysqli_query($link,"UPDATE table SET list3cnt+='1' WHERE list3 LIKE '%book%'");

Right now if I use this on multiple sets of data, I am sending 3 queries. 现在,如果我在多组数据上使用它,我将发送3个查询。 Each query takes more time if passed using mysqli_query in PHP, so I am looking for a 3in1 MYSQL solution with IF's and conditions in MYSQL directly. 如果在PHP中使用mysqli_query传递每个查询,则将花费更多时间,因此我正在直接在MYSQL中寻找具有IF和条件的3合1 MYSQL解决方案。 And I found something but problem is that this doesn't work, so I am stuck: 我发现了一些问题,但是问题是这行不通,所以我被卡住了:

UPDATE table SET `list1cnt`=(CASE WHEN `list1` LIKE '%book%' THEN (`list1cnt`+'1')) WHERE date<='$date'

You can change multiple columns in an update . 您可以在update更改多个列。 In this case, you want conditional updates: 在这种情况下,您需要条件更新:

UPDATE table
    SET list1cnt = (case when list1 like '%book% then  list1cnt + 1 else list1cnt end),
        list2cnt = (case when list2 like '%book% then  list2cnt + 1 else list2cnt end),
        list3cnt = (case when list3 like '%book% then  list3cnt + 1 else list3cnt end)
        list1cnt += 1
    WHERE list1 LIKE '%book%' or list2 LIKE '%book%' or list3 LIKE '%book%';

You can just use IF : 您可以只使用IF

UPDATE
  `table`
SET
  `list1cnt` = IF (`list1` LIKE '%book%', `list1cnt` + 1, `list1cnt`),
  `list2cnt` = IF (`list2` LIKE '%book%', `list2cnt` + 1, `list2cnt`),
  `list3cnt` = IF (`list3` LIKE '%book%', `list3cnt` + 1, `list3cnt`),

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

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