简体   繁体   English

当该信息是同一表中 GROUP CONCAT 的结果时,如何更新记录中的列?

[英]How can I UPDATE a column in a record when that information is the result of a GROUP CONCAT in the same table?

I cannot determine if this should be something nested or a JOIN.我无法确定这应该是嵌套的还是 JOIN。

Each record has three values from the column value across from their name in the column variable .每条记录都有三个值,它们来自列variable value

I have a successful GROUP CONCAT that combines them into a single text string.我有一个成功的 GROUP CONCAT,它将它们组合成一个文本字符串。

BUT, I need to UPDATE/INSERT the concat value into another variable=>value pair.但是,我需要将 concat 值更新/插入到另一个变量=>值对中。

Such as this.比如这个。 I want each person to have "cityStateZip" in the value for `cust_abc'.我希望每个人在“cust_abc”的value中都有“cityStateZip”。

I believe it's "INSERT" and not update since none of the records have anything in cust_abc yet.我相信它是“INSERT”而不是更新,因为 cust_abc 中还没有任何记录。 But, I'm not quite sure if it shouldn't be UPDATE.但是,我不太确定它是否不应该更新。

id_member id_member variable多变的 value价值
1234 1234 cust_abc客户abc "should show citystatezip" “应该显示 citystatezip”
1234 1234 cust_a cust_a city城市
1234 1234 cust_b客户b state state
1234 1234 cust_c客户 zip zip

I can't get past the error of having the target table being the same in the SELECT FROM.我无法克服目标表在 SELECT FROM 中相同的错误。

I was attempting things like:我正在尝试这样的事情:


INSERT INTO smgqg_themes.value (my group concat) WHEN `variable` = "cust_abc"

This is the group concat that works fine to make the string:这是可以很好地制作字符串的组 concat:

SELECT GROUP_CONCAT
( `value` 
order by case variable 
when 'cust_a' then 1 
when 'cust_b' then 2 else 3 end
SEPARATOR '') 
output
FROM smfqg_themes
WHERE `id_member` IN (1234, 1235, 1236, etc) 
AND `variable`  IN ('cust_a', 'cust_b', 'cust_c')

You can INSERT into a the same table you SELECT from in the same SQL statement.您可以在同一个 SQL 语句中插入到与 SELECT 相同的表中。 I do this all the time.我一直这样做。

The syntax is:语法是:

INSERT INTO <tablename> (<columns...>)
SELECT ...;

The SELECT must return the same columns that you name in the INSERT clause, in the same order. SELECT 必须以相同的顺序返回您在 INSERT 子句中指定的相同列。

If you want an existing row to be updated, but still insert a row if one is missing with the 'cust_abc' varible, then you can use INSERT...ON DUPLICATE KEY UPDATE:如果你想更新现有的行,但如果 'cust_abc' 变量丢失了一行,你仍然插入一行,那么你可以使用 INSERT...ON DUPLICATE KEY UPDATE:

INSERT INTO smgqg_themes (id_member, variable, value)
SELECT id_member, 'cust_abc', 
  GROUP_CONCAT(`value` 
    ORDER BY CASE variable 
    WHEN 'cust_a' THEN 1 
    WHEN 'cust_b' THEN 2 ELSE 3 END
    SEPARATOR '') as v
FROM smgqg_themes
WHERE `id_member` IN (1234, 1235, 1236) 
  AND `variable` IN ('cust_a', 'cust_b', 'cust_c')
GROUP BY `id_member`
ON DUPLICATE KEY UPDATE value = VALUES(value);

Demo: https://dbfiddle.uk/OPJQ1ZXF演示: https://dbfiddle.uk/OPJQ1ZXF

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

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