简体   繁体   English

查询按单列分组

[英]Query grouped by single column

I'd like to spit out database results which are grouped by a parent ID. 我想吐出按父ID分组的数据库结果。

I have the following table: 我有下表:

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

Some of the pages have a parent_id of 0, meaning they do not have a parent. 有些pagesparent_id为0,这意味着它们没有父页面。

Lets say I have the following rows in the pages table: 可以说我在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

Given these rows, I want to output the following on my PHP page: 给定这些行,我想在PHP页面上输出以下内容:

Colors
    Red
    Green
    Blue

Devices
    Mobile
    Desktop
    Tablet

I know that I can use a query to get the rows with a parent_id of 0, and then another query to get the rows with a parent_id of that id . 我知道我可以使用查询来获取parent_id为0的行,然后使用另一个查询来获取parent_idid的行。

Is it possible to write this as a single query? 是否可以将其写为单个查询?

Yes, but it's not pretty: You have a hierarchical data structure (parent/child), and to arrange things in that fashion in a single query requires recursive queries, which mysql doesn't support. 是的,但不是很漂亮:您具有分层数据结构(父/子),并且以这种方式在单个查询中安排事务需要递归查询,而mysql不支持该递归查询。

You'll need to do a self-join for every level of hierarchy you have: 您需要对您拥有的每个层次结构进行自我联接:

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

For every level of your tree, you'll need another join/alias as above. 对于树的每个级别,您都需要如上所述的另一个联接/别名。

I think you are looking the following solution: 我认为您正在寻找以下解决方案:

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

You will get the result as like: 您将得到如下结果:

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

Now you have to arrange it in you php side. 现在,您必须将其安排在您的php端。

Here is the sqlfiddle link: http://sqlfiddle.com/#!9/11fa6/3 这是sqlfiddle链接: http ://sqlfiddle.com/#!9/11fa6/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM