基于值的Mysql更新和选择查询

时间:2017-06-28 16:32:36

标签: mysql sql

我想使用tb_usermetameta_idmeta_key's一个查询在meta_value's上进行更新。这个有可能?

tb_usermeta:

+----+---------+-----------+------------+
| id | meta_id | meta_key  | meta_value |
+----+---------+-----------+------------+
|  1 |       1 | user_nome | user 1     |
|  2 |       1 | user_fone | 99999      |
|  3 |       2 | user_nome | user 2     |
|  4 |       2 | user_fone | 88888      |
+----+---------+-----------+------------+

Ex:数据:
meta_id = 1,meta_key = user_nome,meta_value =用户已更改
    meta_id = 1,meta_key = user_fone,meta_value = 696969

更新后的tb_usermeta:

 +----+---------+-----------+-------------+
 | id | meta_id | meta_key  | meta_value  |
 +----+---------+-----------+-------------+
 |  1 |       1 | user_nome | user changed|
 |  2 |       1 | user_fone | 696969      |
 |  3 |       2 | user_nome | user 2      |
 |  4 |       2 | user_fone | 88888       |
 +----+---------+-----------+-------------+

1 个答案:

答案 0 :(得分:1)

考虑以下内容......

DROP TABLE IF EXISTS eav;

CREATE TABLE eav
(entity INT NOT NULL
,attribute VARCHAR(12) NOT NULL
,value  VARCHAR(20) NOT NULL
,PRIMARY KEY(entity,attribute)
);

INSERT INTO eav VALUES
(1,'user_nome','user 1'),
(1,'user_fone','99999'),
(2,'user_nome','user 2'),
(2,'user_fone','88888');

UPDATE eav 
   SET value = CASE attribute WHEN 'user_nome' THEN 'user changed' 
                              WHEN 'user_fone' THEN '696969' 
                              END 
 WHERE entity = 1;

SELECT * FROM eav;
+--------+-----------+--------------+
| entity | attribute | value        |
+--------+-----------+--------------+
|      1 | user_nome | user changed |
|      1 | user_fone | 696969       |
|      2 | user_nome | user 2       |
|      2 | user_fone | 88888        |
+--------+-----------+--------------+

使用视图执行此操作会很好 - 但我认为MySQL会考虑这样一个事实:您一次更新两个事物'更新多个基础表',这是不允许的。