简体   繁体   English

如何基于同一记录中另一个字段的值更新MySql字段

[英]How to update a MySql field based upon value of another field in the same record

I am trying to update values in a MySQL table and really getting stuck. 我正在尝试更新MySQL表中的值,并且确实卡住了。

Basically I want to update a column's value to 1 where another column (in the same row) = "N". 基本上,我想将一列的值更新为1,其中另一列(在同一行中)=“ N”。 It should be quite simple but I can't fathom it. 它应该很简单,但我无法理解。

UPDATE household SET allowsDogs=1 WHERE allowsCats="N"

In my mind the above query should, for each household if allowsCats="N" then set allowsDogs to 1. But instead I get an empty result set. 在我看来,上述查询应该针对每个家庭,如果allowCats =“ N”,然后将allowDogs设置为1。但是,我得到的是空结果集。

I have also tried variations: 我也尝试过变体:

Update household  set allowsDogs=1 where householdID in (select householdID from household where allowsCats="N") 

Update household  set allowsDogs=1 where householdID in (select householdID from copy_of_household where copy_of_household.allowsCats="N")

I'm just about to write a php script to read in each row and update one at a time....But there must be an easier way... 我正要编写一个php脚本以读取每一行并一次更新一个。...但是必须有一种更简单的方法...

Presumably, you mean one of the following: 大概是以下之一:

UPDATE household
    SET allowsDogs = 1
    WHERE allowsCats = 0;

or 要么

UPDATE household
    SET allowsDogs = 'Y'
    WHERE allowsCats = 'N';

Mixing numbers and characters for flags is like, well, mixing cats and dogs. 混合标记的数字和字符就像混合猫和狗一样。

Your first query is correct, but it should not return result set. 您的第一个查询是正确的,但它不应返回结果集。

To see the result use separate SELECT * FROM household statement. 要查看结果,请使用单独的SELECT * FROM household声明。

The syntax you have specified is correct, and should work. 您指定的语法是正确的,应该可以使用。 I believe this is where you are getting tripped up: 我相信这是您被绊倒的地方:

But instead I get an empty result set. 但是相反,我得到了一个空结果集。

UPDATE queries do not return any result set. UPDATE查询不返回任何结果集。 They do their work and then return an empty result set. 他们完成工作,然后返回空结果集。 However, your client library or application should provide a way for you to see how many records were altered (but not which specific ones). 但是,您的客户端库或应用程序应为您提供一种方法,让您查看更改了多少条记录(但未查看哪些特定记录)。

Further, note that the database server may skip updating a record if all of the fields you are updating already have the new value you are assigning. 此外,请注意,如果要更新的所有字段已经具有要分配的新值,则数据库服务器可能会跳过记录的更新。 For example, if all of the records in the table with the field allowCats equal to "N" also have their allowDogs field equal to 1 then the database server may not include those rows in the total number of rows updated, since they were not actually changed. 例如,如果表中所有字段allowCats等于"N"也都具有其allowDogs字段等于1则数据库服务器可能不将这些行包括在更新的总行数中,因为它们实际上并不是改变。

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

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