I want to use group_concate in my queries. I have two tables which are wla_user and wla_factory. In table wla_user, the column factory_id contains 1,8, while at wla_factory, id 1= factory 1 while id 8 = factory 8. While during the query, column factory_name, only show factory 1.
What I want is suppose factory 1, factory 8. Below is my current code:
SELECT wla_user.id, wla_user.name, wla_user.email, GROUP_CONCAT(wla_user.factory_id), GROUP_CONCAT(wla_factory.factory_name)
FROM wla_user
INNER JOIN wla_factory ON wla_user.factory_id = wla_factory.id
WHERE wla_user.email = '[email protected]' AND wla_user.status = 1 GROUP BY wla_user.id
Can anyone know which part I missed?
2
Answers
You are almost there, your refined query will be:
The resource to refer to:
https://www.geeksforgeeks.org/mysql-group_concat-function/
Hope this helps.
I am not 100% sure that my understanding of your question is correct. I am assuming the below sample data with CSV value for
wla_user.factory_id
:wla_user
wla_factory
Your current join
wla_user.factory_id = wla_factory.id
leads towla_user.factory_id
being implicitly cast to an integer, which is why you are only seeing one value from thewla_factory
table.As pointed out by Akina, you can use FIND_IN_SET() to join based on your CSV column:
The above query will work but, again as pointed out by Akina, you should normalise your data. Working with serialised data in columns is problematic (hard to query, cannot use indices, etc) when you need to query based on that data. Instead you should move the relation to a many-to-many table:
Then your query becomes:
And the output is:
Here’s a db<>fiddle