2012-04-12 31 views
0

MySQL數據庫MySQL來1個陣列

產品

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,但不會在以後造成很多性能問題?也沒有一個字符限制?

回答

0

你不能沒有第一迭代所需的數據超過產品的結果,因爲它是一個一對多的關係

看到這個答案Displaying data from two tables with many-to-many relation using PHP/CodeIgniter

這是笨,但你可以得到的想法

+0

是不是很不好,雖然運行在一個循環的查詢? – Jarritos 2012-04-12 04:40:40

+0

根據您的要求,沒有其他選擇。在一個查詢中不可能,因爲產品中的每一行都有很多行 – Broncha 2012-04-12 05:05:35

+0

如果我採用了不同的格式,那麼可以在沒有循環的情況下做到這一點? – Jarritos 2012-04-12 09:55:39

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

+0

對於其他方法,我不是已經通過idProduct做到了這一點嗎?這是外鍵。也有多個評分結果。在我看來,循環這將是一件壞事。 – Jarritos 2012-04-12 09:54:51

+0

對不起,我以爲你可能會使用MyISAM,只是製作你自己的外鍵,而不是利用InnoDB內置外鍵支持的能力。 – 2012-04-12 15:44:54