Search code examples
mysqlsubqueryconcatenation

How to use WHERE in CONCAT in mysql


Here is my scenario as beginner in mysql.

There are 2 tables.

  • usermeta has 3 columns user_id, meta_key, meta value
  • users_role has 2 columns uid, rid.

I need to insert rows in wp_usermeta based on users_roles.rid value.

  • User_id from users_roles (users_role.uid matches wp_usermeta.user_id).
  • Meta_key is set to dokan_profile_settings.
  • Meta_value should be a CONCAT of :

textA + meta_value from rows with meta_key dokan_site_name already existing in wp_usermeta + textB.

There is my problem. I can't figure out the right way to achieve the CONCAT properly.

When i run this i get : #1242 - Subquery returns more than 1 row

INSERT INTO usermeta (
    user_id, 
    meta_key, 
    meta_value
    )
SELECT
    uid,
    'dokan_profile_settings',
    CONCAT('textA', (SELECT usermeta.meta_value FROM usermeta WHERE usermeta.meta_key LIKE 'dokan_store_name'), 'textB') 
AS meta_value
FROM users_roles WHERE rid LIKE '4'; 

If i just run the SELECT part of the CONCAT, as pointed out in Paul's comment :

SELECT usermeta.meta_value FROM usermeta 
WHERE usermeta.meta_key LIKE 'dokan_store_name'

I get the intended result, but i can't figure out why the whole query fails.


Solution

  • As the error message states, you can't use a subquery that returns more than one string value in a CONCAT() function. An easy way to solve this would be to GROUP_CONCAT() the results of your subquery: CONCAT('textA', (SELECT GROUP_CONCAT(usermeta.meta_value) FROM usermeta WHERE usermeta.meta_key LIKE 'dokan_store_name'), 'textB')