簡體   English   中英

查詢按單列分組

[英]Query grouped by single column

我想吐出按父ID分組的數據庫結果。

我有下表:

`pages`
    `id` int
    `parent_id` int
    `title` varchar

有些pagesparent_id為0,這意味着它們沒有父頁面。

可以說我在pages表中包含以下行:

id | parent_id | title
1  | 0         | Colors
2  | 1         | Red
3  | 1         | Green
4  | 1         | Blue
5  | 0         | Devices
6  | 5         | Mobile
7  | 5         | Desktop
8  | 5         | Tablet

給定這些行,我想在PHP頁面上輸出以下內容:

Colors
    Red
    Green
    Blue

Devices
    Mobile
    Desktop
    Tablet

我知道我可以使用查詢來獲取parent_id為0的行,然后使用另一個查詢來獲取parent_idid的行。

是否可以將其寫為單個查詢?

是的,但不是很漂亮:您具有分層數據結構(父/子),並且以這種方式在單個查詢中安排事務需要遞歸查詢,而mysql不支持該遞歸查詢。

您需要對您擁有的每個層次結構進行自我聯接:

SELECT parent.*, child.*
FROM yourtable AS parent
LEFT JOIN yourtable AS child ON parent.id = child.parent_id

對於樹的每個級別,您都需要如上所述的另一個聯接/別名。

我認為您正在尋找以下解決方案:

SELECT 
  t1.title as parent, t2.title
FROM 
  pages AS t1
LEFT JOIN pages AS t2 
  ON t1.id = t2.parent_id
WHERE
  t2.id IS NOT NULL

您將得到如下結果:

parent  title
Colors  Red
Colors  Green
Colors  Blue
Devices Mobile
Devices Desktop
Devices Tablet

現在,您必須將其安排在您的php端。

這是sqlfiddle鏈接: http ://sqlfiddle.com/#!9/11fa6/3

暫無
暫無

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

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