简体   繁体   English

MySQL从两个表变成1个数组

[英]Mysql from two tables into 1 array

MySQL DB MySQL数据库

Product 产品

id        name               
1         Product #1            
2         Product #2                
3         Product #3            
4         Product #4 

Review 评论

id        idUser    idProduct  Rating
1         1         1          A Long Boring Review that is up to 500 characters
2         1         2          A Long Boring Review that is up to 500 characters   
3         2         4          A Long Boring Review that is up to 500 characters
4         1         1          A Long Boring Review that is up to 500 characters

What would be the best way of pulling info from both these databases and arranging them as such: 从这两个数据库中提取信息并将其安排成这样的最好方法是:

[0] => stdClass Object
        (
            [id] => 1
            [name] => Product #1
            [reviews] => Array(
                [0]=>
                    (
                        [id] => "1"
                        [idUser] => "1"
                        [idProduct] => "1"
                        [Rating] => "A Long Boring Review that is up to 500 characters"
                    )
                [1] = >
                    (...
            )
        )
[1] => stdClass Object
        (
            [id] => 2
            [name] => Product #2
            [reviews] => Array(
                [0]=>
                    (
                        [id] => "1"
                        [idUser] => "1"
                        [idProduct] => "2"
                        [Rating] => "A Long Boring Review that is up to 500 characters"
                    )
                [1] = >
                    (...
            )
        )

I was thinking about using GROUP_CONCAT but wont that cause a lot of performance issues later on? 我当时正在考虑使用GROUP_CONCAT,但是以后会不会引起很多性能问题? Also doesn't that have a character limit? 还没有字符限制吗?

You cannot get the desired data without first iterating over the result of Product, as it is a One to Many relationship 如果不先迭代乘积的结果,就无法获得所需的数据,因为它是一对多的关系

See this Answer Displaying data from two tables with many-to-many relation using PHP/CodeIgniter 查看此答案使用PHP / CodeIgniter从具有多对多关系的两个表中显示数据

It is for codeigniter, but you can get the idea 它是用于代码点火器的,但是您可以理解

This will give you a one dimensional result if there is only one review: 如果只有一个评论,这将为您提供一维结果:

SELECT `id`,`name`,(SELECT `Review`.`Rating` FROM `Review` WHERE `Review`.`idProduct` = `id`) as `rating` FROM `Product` WHERE 1;

For multiple reviews you'll need to loop through and build the structure for each product. 对于多条评论,您需要遍历并构建每种产品的结构。

For another approach, see the answer for this question: How to create relationships in MySQL 对于另一种方法,请参见以下问题的答案: 如何在MySQL中创建关系

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

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