簡體   English   中英

SQL:超越INNER JOIN(由於缺少更好的標題)

[英]SQL: Beyond INNER JOIN (for lack of a better title)

環境:
-PHP 5.3.5
-Oracle 11g數據庫

表名稱:tips_categories

id   category   picture  
1    a          e.jpg  
2    b        f.jpg  
3    c        g.jpg

表名稱:提示

id   tips_categories_id   tip
1    3                       This is a tip.
2    2                       This is another tip.
3    1                       This is yet another tip.

所需結果:

$array_name['tips']
    [0]
        category => a
        picture => e.jpg
        tips
            [0] => This is yet another tip.
    [1]
        category => b
        picture => f.jpg
        tips
            [0] => This is another tip.
    [2]
        category => c
        picture => g.jpg
        tips
            [0] => This is a tip.

編寫一個返回所需結果的查詢超出了我目前對SQL的了解。 INNER JOIN不返回所需的結果。 如果不能在一個查詢中完成,那么我猜將不得不使用以下兩個查詢:

從tips_categories中選擇ID,類別,圖片
從提示中選擇提示WHERE tips_categories_id = id

我非常感謝有關如何在一個語句中編寫此查詢的建議。 謝謝 :-)

查詢不會返回分層結果集。 因此,您試圖做的事情是不可能的。

您可以編寫一個簡單的內部聯接查詢,按id排序,然后在結果集上進行自我迭代,並在每次id更改時將新條目添加到數組中,從而創建一個數組。

查詢:

SELECT tips.id,category,picture, tip
  FROM tips_categories
 INNER JOIN tips on (tips_categories_id = id)
 ORDER BY tips.ip

因此,您的結果集將類似於:

 id   category   picture  tip
 1    a          e.jpg    This is yet another tip A01.
 1    a          e.jpg    This is yet another tip A02.
 1    a          e.jpg    This is yet another tip A03.
 2    b          f.jpg    This is another tip B01.
 2    b          f.jpg    This is another tip B02.
 3    c          g.jpg    This is a tip C01.

如果您在tips表上有更多條目。

您使用PHP進行迭代,並在數組上產生所需的結果。 它應該非常簡單明了。

好吧:

SELECT c.id, c.category, c.picture, t.tip
FROM tips_categories AS c
INNER JOIN tips AS t
    ON t.tips_categories_id = c.id

當然會返回您想要的數據,但是小費只會是第4列,而不是某種層次結構。

您正在使用什么從結果構建陣列?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM