MySQL更新所有以相同名称开头的列

编程入门 行业动态 更新时间:2024-10-28 01:24:15
本文介绍了MySQL更新所有以相同名称开头的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个动态表,名为"products",具有多种语言. 表格列如下所示:

I have a dynamic table named 'products' with multiple Languages. The table columns looks like this:

id, product_id, store_de, store_en, store_fr, store_es... etc

语言可以更多或更少.

现在,我想更新此表并将所有以"store_"开头的列设置为值1.

Now I want to update this table and set all columns beginning with "store_" to value 1.

我尝试了以下操作:

$stmt = $dbh->prepare( "UPDATE products SET `store_%` = ? WHERE product_id = ?" ); $stmt->execute( array( 1, $lastID ) );

我收到以下错误消息:

SQLSTATE [42S22]:找不到列:1054中的未知列'store%' 字段列表"

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'store%' in 'field list'

是否可以更新以"store_"开头的所有列?还是必须列出所有列?

Is there a way to update all columns beginning with 'store_' or do I have to list all the columns?

根据jekaby的回答,这里是对我有用的完整解决方案:

Based on the answer from jekaby here is the full solution that worked for me:

$get_stores = $dbh->prepare("SHOW COLUMNS FROM products_active WHERE field REGEXP '^store'"); $get_stores->execute(); $stores = $get_stores->fetchAll(); $update_string = ""; $first_store = true; foreach($stores as $store) { if(!$first_store) { $update_string .= ", "; } else { $first_store = false; } $update_string .= $store['Field']." = '".$status."'"; } $update_activity = $dbh->prepare("UPDATE products_active SET $update_string WHERE product_id = ?"); $update_activity->execute(array($product_id));

推荐答案

您不能像这样store_%-它是表中不存在的列,因为它是在您的错误中编写的.

You can not do like this store_% - it is nonexistent column in table as it is written in your error.

您应该获得所有名称类似于/^store_/(regexp)的列.然后更新列出了这些字段的所有这些字段.

You should get all colums with names like /^store_/ (regexp). And than update all this fields having listed them.

mysql> SHOW COLUMNS FROM products where field REGEXP '^store_'

比从字段"中收集所有字段...您可以了解更多有关如何获取所有列的信息这里.

Than collect all fields from 'Field'... You can read more how to get all columns here.

更多推荐

MySQL更新所有以相同名称开头的列

本文发布于:2023-10-16 15:49:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:开头   名称   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!