基于Count的限制

时间:2011-01-15 13:40:32

标签: php sql mysql

我将一个表用于类别和内容。

pid字段中的类别值为0.

例如:

示例表

--------------------------
id | pid | name
--------------------------
1  | 0   | Some catgory 1
--------------------------
2  | 1   | Some content of first category
--------------------------
3  | 1   | Other content of first cat
--------------------------
4  | 0   | Second category
--------------------------
5  | 0   | Category number 3
--------------------------
6  | 5   | Content of category 3
--------------------------
7  | 4   | Content of 2 cat
--------------------------
8  | 5   | Content of 3 cat
--------------------------
9  | 5   | Other Content of 3 cat
--------------------------
10 | 5   | One more content of 3 cat
--------------------------
11 | 4   | Content of 2 cat
--------------------------
12 | 5   | One more content of 3 cat
--------------------------
13 | 1   | First cat content
--------------------------
14 | 1   | Other content of 1 cat

如何在一个查询中获取所有类别和10个内容项?

1 个答案:

答案 0 :(得分:5)

要在单个查询中获取两个单独查询的结果,请使用UNION ALL:

SELECT id, pid, name
FROM yourtable
WHERE pid = 0
UNION ALL
(
    SELECT id, pid, name
    FROM yourtable
    WHERE pid <> 0
    LIMIT 10
)