[英]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. 当我做我的请求并在php中使用它时,拥有大量具有相同结果的行是没有用的。 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 ? 用mysql可以吗? Without an UDF ?
没有UDF? And with an UDF ?
用UDF?
Thank you, Kevin 谢谢你,凯文
Do you object to using GROUP_CONCAT
? 你反对使用
GROUP_CONCAT
吗? This would give you a nice delimited list (Assuming the ean
value will never have your delimiter within): 这会给你一个很好的分隔列表(假设
ean
值永远不会有你的分隔符):
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 此外,这是我在应用此逻辑时发现的qeustion: mySql - 使用逗号分隔值列表创建连接
See GROUP_CONCAT() . 见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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.