简体   繁体   English

MySQL 和 PHP - 有效地获取与每一行关联的行和 arrays

[英]MySQL and PHP - Efficiently get rows and arrays associated with each row

I have two tables:我有两张桌子:

table1:表格1:

ID | user | info
------------------
1    1      data1
2    1      data2
3    2      data3

table2:表2:

table1_id | array_info
------------------------
1             a  
1             b
2             a
3             d
3             g
3             m

How can I efficiently return the rows associated with a user such that I get info and an array of that ID's associated array_info?如何有效地返回与用户关联的行,以便我获取信息和该 ID 的关联 array_info 的数组?

For instance, a query like "select ID, info from table1 where user = 1" but would also return [a,b] from table2 so that the result would be something like [1, data1, [a, b]] with the first row and [2, data2, [a]] with the second row.例如,像“select ID, info from table1 where user = 1”这样的查询,但也会从 table2 返回 [a,b],因此结果将类似于 [1, data1, [a, b]]第一行和 [2, data2, [a]] 与第二行。 Similarly, "...where user = 2" should return something like [3, data3, [d, g, m]].类似地,“...where user = 2”应该返回类似 [3, data3, [d, g, m]] 的内容。 I don't think MySQL returns things quite like this, but perhaps PHP can smooth over the input of a left join?我不认为 MySQL 返回的东西很像这样,但也许 PHP 可以平滑左连接的输入? It seems wasteful to replicate all the data in info if MySQL returns a separate row for each array_info, but I'm not sure there's another way.如果 MySQL 为每个 array_info 返回一个单独的行,则复制 info 中的所有数据似乎很浪费,但我不确定还有其他方法。

You could use a GROUP_CONCAT with a JOIN and then when you iterate over the results, use explode() to convert the concatenated string to an array.您可以将 GROUP_CONCAT 与 JOIN 一起使用,然后在迭代结果时,使用 explode() 将连接的字符串转换为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM