MySQL:更新第一个可用列为空的行


MySQL: Update row where the first available column is empty

我有一个表,用来跟踪用户与其网站其他方面之间的一些关联。

我需要能够获得第一个可用行并更新其中的一两列。。。标准是CCD_ 1列是否已经被使用。

id | tag_id | user_id | product_id

如果一行有一个可用的标签,而没有分配user_id,我希望能够使用并更新该行以获得最新购买的产品。

1 | 100001 | 29 | 66  
2 | 100002 | 0  | 0 
3 | 100003 | 0  | 0

正如你所看到的,第二排将是第一个符合条件的候选人。

我只是不确定SQL需要什么才能实现

UPDATE yourTablename SET user_id = 'your value for userid',
product_id='ur value for productid' WHERE id=(select min(id) where user_id='0');

已经告知的替代方法是有效的,但如果您的表具有id 排序

UPDATE yourTablename SET user_id = 'your value for userid',
product_id='ur value for productid' where user_id='0' LIMIT 1;

如果我理解正确,您希望更新第一个可用的空(不是NULL,而是空)user_id行。怎么样?

UPDATE users 
SET user_id = 'user_value_here' 
WHERE user_id='' 
LIMIT 1

如果您的索引是ASC排序的,那么下面的查询应该会按顺序找到第一个结果。

看看小提琴。

UPDATE table SET user_id = 1 WHERE user_id IS NULL LIMIT 1

您可以将IS NULL替换为空user_id的条件。