Mysql从两个表变为1个数组

时间:2012-04-12 04:30:00

标签: php mysql

MySQL DB

产品

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

评分

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

从这两个数据库中提取信息并将其排列的最佳方法是什么:

[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] = >
                    (...
            )
        )

我正在考虑使用GROUP_CONCAT,但是之后会不会导致很多性能问题?还有没有字符限制吗?

2 个答案:

答案 0 :(得分:0)

如果没有首先迭代Product的结果,就无法获得所需的数据,因为它是一对多的关系

请参阅此答案Displaying data from two tables with many-to-many relation using PHP/CodeIgniter

它适用于codeigniter,但你可以得到这个想法

答案 1 :(得分:0)

如果只有一个评论,这将为您提供一维结果:

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

对于多次审核,您需要循环并构建每种产品的结构。

对于另一种方法,请参阅此问题的答案:How to create relationships in MySQL