我想要 select 数据,然后使用带有 concat 的更新来附加一些文本 (Mysql)

I want to select data then use update with concat to append some text (Mysql)

我有两个模式 arkdb 和 kalscrosschat。 Id 是两者的主键。

arkdb 有一个 table 叫做 players 和 fields

Id SteamId            PermissionGroups

1  76561197969383152  Default

2  76561197969383154  Default

Kalscrosschat 有一个 table 称为 discordsteamlinks amd fields

Id  SteamId           DiscordId            InviteCode

1   76561198032704712 150054663054426113   NU123

2   76561198032704714 150054663054426113   ME123

我有一个 select 查询。

    Select
        kalscrosschat.discordsteamlinks.DiscordId,
        kalscrosschat.discordsteamlinks.SteamId,
        arkdb.players.SteamId As SteamId1,
        arkdb.players.PermissionGroups
    From
        kalscrosschat.discordsteamlinks Inner Join
        arkdb.players On arkdb.players.SteamId = kalscrosschat.discordsteamlinks.SteamId
    Where
        arkdb.players.PermissionGroups Not Like '%Discord%'

然后我需要更新 arkdb.players.permissionsgroups 以将 Discord 附加到最后。

所以1 76561197969383152 Default会变成1 76561197969383152 Default,Discord

我该怎么做???

假设 arkdb.players table 有 id 列作为主键,考虑使用以下带有适当别名的语句:

UPDATE arkdb.players pp
  JOIN (
        SELECT p.id, CONCAT(p.PermissionGroups,',', d.DiscordId) AS pg
          FROM kalscrosschat.discordsteamlinks AS d
          JOIN arkdb.players AS p
            ON p.SteamId = d.SteamId
         WHERE p.PermissionGroups NOT LIKE '%Discord%'
       ) dp ON  dp.id = pp.id 
   SET pp.PermissionGroups = dp.pg

以便将 Discord 的值添加到该列值的末尾。

您可以像这样在 UPDATE 语句中连接表:

UPDATE arkdb.players p
INNER JOIN kalscrosschat.discordsteamlinks d  on p.SteamId = d.SteamId
SET p.PermissionGroups = CONCAT(p.PermissionGroups, ',', 'Discord')
WHERE p.PermissionGroups NOT LIKE '%Discord%'

或者如果您在 PermissionGroups 列中有 null

UPDATE arkdb.players p  
INNER JOIN kalscrosschat.discordsteamlinks d on p.SteamId = d.SteamId
SET p.PermissionGroups = CONCAT_WS(',', p.PermissionGroups, 'Discord')
WHERE p.PermissionGroups NOT LIKE '%Discord%' OR p.PermissionGroups IS NULL