简体   繁体   中英

Convert result from a left join to an array (or json or whatelse)

I actually have these tables :

- Table games -
ID
Name

- Table ean -
ID
ID_games
EAN

And I have this request :

SELECT games.*, ean.EAN
FROM games
LEFT JOIN ean ON (games.ID = ean.ID_games)

The result will be something like this :

| 1 | Half Life | 358958595 |
| 1 | Half Life | 589584859 |
| 2 | Half Life 2 | 385953684 |
| 2 | Half Life 2 | 585100335 |
etc.

When I do my request and use it in php, it is not useful to have a lot of line with about the same results. I would like to do something like this :

SELECT games.*, ConvertToArray(ean) AS ean_array
FROM games
LEFT JOIN ean ON (games.ID = ean.ID_games)

And have results like this :

| 1 | Half Life | (358958595,589584859) |
| 2 | Half Life 2 | (385953684,585100335 ) |
etc.

Is it possible to that with mysql ? Without an UDF ? And with an UDF ?

Thank you, Kevin

Do you object to using GROUP_CONCAT ? This would give you a nice delimited list (Assuming the ean value will never have your delimiter within):

SELECT       games.*, GROUP_CONCAT(ean.EAN) AS ean_list,
FROM         games
  LEFT JOIN  ean
  ON         games.ID = ean.ID_games
GROUP BY     games.ID, games.name

Resulting in:

| 1 | Half Life   | 358958595,589584859 |
| 2 | Half Life 2 | 385953684,585100335 |

Also, here's a qeustion I found with this logic applied: mySql - creating a join using a list of comma separated values

See GROUP_CONCAT() .

Example can be found here .

Your query would look something like:

SELECT games.*, GROUP_CONCAT(DISTINCT ean) AS ean_array
FROM games
LEFT JOIN ean ON (games.ID = ean.ID_games)
GROUP BY games.ID

Try this one:

SELECT g.id, GROUP_CONCAT(CAST(e.ean AS CHAR) SEPARATOR ', ')
FROM games g
LEFT JOIN ean e ON g.id = e.id_games
GROUP BY g.id;

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