简体   繁体   中英

How to make proper UPDATE query?

Good day guys,

I'm trying to UPDATE the whole column in my table, with the result of another SELECT query. The query I'm trying to run is:

UPDATE 
    clients 
SET 
    activity = (
        SELECT 
            IFNULL(
                GROUP_CONCAT(
                    CONCAT(
                        ' ',
                        o.event_abr, 
                        ' ',
                        IFNULL(CONCAT(o.quantity,'x'),''), 
                        IFNULL(o.price,'')
                    )
                )
            ,'') 
        FROM 
            clients c 
        LEFT OUTER JOIN 
            orders o 
        ON 
            (c.id = o.client_id) 
        WHERE 
            c.id = clients.id
    )

I'm getting #1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '<>'

However, if i run just SELECT, it works perfectly with the only change of clients.id to some integer

Please help :)

I am guessing you just want a correlated subquery:

UPDATE clients c
    SET activity = (SELECT COALESCE(GROUP_CONCAT(' ', o.event_abr,  ' ',
                                                 COALESCE(CONCAT(o.quantity, 'x'), ''), 
                                                 COALESCE(o.price, '')
                                                )
                                   ), '') 
                    FROM orders o 
                    WHERE c.id = o.client_id
                   );

Notes:

  • In MySQL you cannot refer to the table being updated outside the UPDATE clause. You could express this as a JOIN , but you have already gone down the path of a subquery.
  • CONCAT() is not needed with GROUP_CONCAT() . It takes an arbitrary number of arguments.
  • COALESCE() is ANSI standard. Hence I prefer it.
  • Your GROUP_CONCAT() is strange, starting with a space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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