2015-08-25 68 views
0

類別表,限制的記錄我有兩個表:PHP和MySQL的加入每

項目

ID  Name    Model_ID 
--------------------------------- 
1  2010 Audi L1  1 
2  2014 BMW X2   2 
3  2015 Acura L3  3 
4  2016 BMW X5   2 
5  2012 BMW X3   2 
6  2013 BMW X4   2 
7  2015 Acura L1  3 
8  2011 Acura L2  3 
9  2011 Audi L5  1 
10  2012 Audi L6  1 

品牌

Model_ID  Title 
--------------------- 
1    Audi 
2    BMW 
3    Acura 

而下面的查詢:

SELECT 
    b.name, 
    i.title, 
    FROM 
    items AS i 
    INNER JOIN brands AS b 
     ON b.Model_ID = i.Model_ID 
    WHERE i.status = 1 
    ORDER BY i.created DESC; 

的以上產生工作陣列:

Array 
(
    [0] => stdClass Object 
     (
      [name] => 2010 Audi L1 
      [title] => Audi 
     ) 

    [1] => stdClass Object 
     (
      [name] => 2014 MBW X5 
      [title] => BMW 

     ) 

     ... 
) 

比我使用自定義函數來遍歷數組,並最終與

Array 
(
    [Acura] => Array 
     (
      [0] => stdClass Object 
       (
        [name] => 2015 Acura L1 
        [title] => Acura 
       ) 

      ... 
     ) 

    [BWM] => Array 
     (
      [0] => stdClass Object 
       (
        [name] => 2016 BMW X5 
        [title] => BWM 
       ) 

      ... 
     ) 
    [Audi] => Array 
     (
      [0] => stdClass Object 
       (
        [name] => 2010 Audi L1 
        [title] => Audi 
       ) 
      ... 
     )  
) 

現在我可以用foreach循環,並限制每個品牌展示物品的X號,但這個想法是做它在數據庫中,所以我不希望所有記錄都被拉下來,而是希望能夠限制每個品牌5個項目。

注意:我沒有列出表格字段的其餘部分,例如創建的,用於對記錄進行排序。

+0

我錯了還是那個查詢都混淆了,所以它實際上並不匹配表列? – RiggsFolly

+0

@ RiggsFolly查詢是正確的,根據我的說明,我沒有包括其餘的字段,只有需要的字段。 – Alko

+0

'我'沒有'標題''B'確實有'標題'。 'b'沒有'name','i'沒有'name'? – RiggsFolly

回答

0
  1. 獲得品牌:

$ Q = 'SELECT MODEL_ID AS標識對品牌的ORDER BY標題ASC';
$ r = mysql_query($ q);
$ model_ids = array();
while($ brand = mysql_fetch_assoc($ r)){$ model_ids [] = $ brand ['id']; }

  • 然後使生成像從第一步驟或其它地方收集此使用MODEL_ID-S選擇查詢(例如:從搜索表單):

  • $q = array(); 
    foreach($mode_ids AS $model_id) { 
        $q[] = '(SELECT b.name, i.title FROM items AS i INNER JOIN brands AS b ON b.Model_ID = i.Model_ID WHERE b.Model_ID = '.(int)$model_id.' AND i.status = 1 ORDER BY i.created DESC LIMIT 5)'; 
    } 
    
    if(!empty($q)) { 
        $q = implode(' UNION ALL ', $q); 
        $r = mysql_query($q); 
        while($record = mysql_fetch_object($r)) { 
         var_dump($record); 
        } 
    } 
    

    的結果,我們會得到結果查詢的記錄:

    (SELECT b.name, I.標題FROM 項AS i的 INNER JOIN品牌爲B ON b.Model_ID = i.Model_ID WHERE b.Model_ID = 1 AND i.status = 1個ORDER BY i.created DESC LIMIT 5)

    UNION ALL

    (SELECT b.name, I.標題FROM 項AS i的 INNER JOIN品牌爲b ON b.Model_ID = i.Model_ID WHERE b.Model_ID = 2和i.status = 1 ORDER BY i.created DESC LIMIT 5)

    UNION ALL

    (SELECT b.name, i。標題FROM 項目,如我 INNER JOIN品牌爲B ON b.Model_ID = i.Model_ID WHERE b.Model_ID = 3,i.status = 1個ORDER BY i.created DESC LIMIT 5)