MySQL JOIN 包装成一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3132324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:26:07  来源:igfitidea点击:

MySQL JOIN wrapping into an array

mysql

提问by Mihai Iorga

I have some minor problem with an SQL query. I have to select data from multiple tables like:

我的 SQL 查询有一些小问题。我必须从多个表中选择数据,例如:

offers:

优惠

| id | offer      | info  
| 1  | City break | information

pictures:

图片

| id | id_offer | picture_name  | title  
| 1  | 1        | bucharest.jpg | Bucharest  
| 2  | 1        | london.jpg    | London

sql query:

sql查询

SELECT offers.* as t1, pictures.* as t2
FROM offers  
JOIN t2 ON t1.id=t2.id_offer  
WHERE t1.id = '1'

The code is much larger but I don't understand how to wrap results from t2 into an array. Because the length of the array returned is made by t2 which is the pictures table. This will return an array with 2 objects.

代码要大得多,但我不明白如何将 t2 的结果包装到数组中。因为返回的数组的长度是由图片表 t2 构成的。这将返回一个包含 2 个对象的数组。

It is possible to return one object in the array with both pictures in it?

可以返回数组中的一个对象,其中包含两张图片吗?

回答by Quassnoi

MySQLdoes not support array datatypes.

MySQL不支持数组数据类型。

You can return a comma separated list of values instead:

您可以改为返回逗号分隔的值列表:

SELECT  o.*, GROUP_CONCAT(picture_name ORDER BY p.id)
FROM    offers o
JOIN    pictures p
ON      p.id_offer = o.id
GROUP BY
        o.id

回答by Naktibalda

Arrays doesn't exist in mysql. But you can use GROUP_CONCATto return all images in comma separated list

mysql 中不存在数组。但是您可以使用GROUP_CONCAT以逗号分隔的列表形式返回所有图像

SELECT offers.*, GROUP_CONCAT(t2.picture_name) AS pictures
FROM offers AS t1
JOIN pictures AS t2 ON t1.id=t2.id_offer
WHERE t1.id = '1' 
GROUP BY t1.id