PHP 如何设置脚本从两个字段中获取两个数值,将它们添加并更新到第三个字段
我有一个包含各种字段的表,其中 2 个字段包含 1 到 50 之间的数字。
我需要帮助设置一个脚本,该脚本将自动将两个设置字段添加起来,并将总计插入到每个单独记录的第三个字段中,以获取所有记录桌子。
我一直在创建这个,因为有些记录会有 0 或 NULL 值。
请帮助:)
我认为我可以纯粹用 SQL 来完成此操作,但我发现的最接近的是:
Alter table Mytable add column Keywords varchar(255);
update Mytable set Keywords = concat(Categories, ' ', Tags);
显然我不需要添加列等。PHP 或 SQL 解决方案都很棒。
举个例子,以防我没有很好地解释这一点,这让我很困惑,
Column 1 - Field Value: 20
Colum 2 - Field Value 20
Add Colum 1 + Colum 2 = 40
Insert 40 into Colum 3
谢谢
I have a table with various fields 2 of which contain a number between 1 and 50.
I need help setting up a script that will automatically take two set fields add them and insert the total into a third field for each indivdual record for all records in the table.
I'm stuck in creating this because some records will have 0 or NULL values.
Please help :)
I've think I may be able to do this purely in SQL but the closest i found was this:
Alter table Mytable add column Keywords varchar(255);
update Mytable set Keywords = concat(Categories, ' ', Tags);
Obviously I would not need to add the column etc. Either a PHP or SQL solution would be fantastic.
Example in case I'mm not explaining this well it's confusing me a lot
Column 1 - Field Value: 20
Colum 2 - Field Value 20
Add Colum 1 + Colum 2 = 40
Insert 40 into Colum 3
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用纯 SQL 来执行此操作。
如果两列都存储为数字:
如果它们存储为字符:
You should do this in plain SQL.
If both columns are stored as numbers:
If they are stored as characters:
尝试以下操作:
UPDATE Mytable SET column3 = column2 + column1
这应该适用于 0 ,但是如果您在任何一个中都有 NULL 值
添加列,您将在结果字段中得到 NULL,因此在这种情况下,查询会略有不同,
例如 if
Column1 可能有空值,那么查询应该是
UPDATE Mytable SET column3 = IFNULL(column1 ,0) + column2
如果两个字段都可以有 NULL 值,那么
UPDATE Mytable SET column3 = IFNULL(列1,0) + IFNULL(列2,0)
Try the following:
UPDATE Mytable SET column3 = column2 + column1
this should work for 0 , however if you have got NULL values in any of the
adding column you will get a NULL in the result field, so in that case the query is slightly different
for e.g. if
Column1 may have null values, then the query should be
UPDATE Mytable SET column3 = IFNULL(column1 ,0) + column2
and if both the fields can have NULL values then,
UPDATE Mytable SET column3 = IFNULL(column1 ,0) + IFNULL(column2 ,0)
这应该可以
用您的表和列替换 [TABLE_NAME] 和 col1、col2、col3
This should do it
Replace [TABLE_NAME] and col1, col2, col3 with your tables and columns
或者
避免 Column1 上出现 NUL
or
to avoid NULs on Column1