Domanda

I have a problem to implement this:

UPDATE users
INNER JOIN relations_colors ON (relations_colors.user_id = users.id)
INNER JOIN colors ON (colors.id = relations_colors.color_id)
SET search_cache = GROUP_CONCAT( colors.name SEPARATOR " ")

phpmyadmin says: "#1111 - Invalid use of group function", how can I fix?

È stato utile?

Soluzione

I think something like this will perform the update operation you are looking for:

UPDATE users u
  JOIN ( SELECT r.user_id
              , GROUP_CONCAT(c.name SEPARATOR ' ') AS search_cache 
          FROM relations_colors r
          JOIN colors c ON c.id = r.color_id
         GROUP BY r.user_id
       ) s
    ON u.id = s.user_id
   SET u.search_cache = s.search_cache

Note that this will update only rows in the users table that have a matching row from relations_colors/colors.

To update ALL rows of users, you'd want to include the LEFT keyword before the JOIN keyword to get an "outer join"; that would set the search_cache column to NULL for users that didn't have any matching rows.

To make the result more deterministic, we'd typically include an ORDER BY clause inside the GROUP_CONCAT function, for example:

GROUP_CONCAT(c.name SEPARATOR ' ' ORDER BY c.id)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top