0

数据库

产品

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 但这不会在以后引起很多性能问题吗?也没有字数限制吗?

4

2 回答 2

0

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

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

对于多个评论,您需要循环并为每个产品构建结构。

对于另一种方法,请参阅此问题的答案:如何在 MySQL 中创建关系

于 2012-04-12T04:45:50.430 回答
0

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

请参阅此答案使用 PHP/CodeIgniter 显示具有多对多关系的两个表中的数据

它适用于codeigniter,但您可以理解

于 2012-04-12T04:35:04.280 回答