我有一个名为category的表,其中有3列:id, name, parent_id
。
ID name group_id
== == ==
1 haim 1
2 gil 2
3 alon 1
4 idan 1
5 shai 3
6 adi 2
7 itay 3
8 aviram 1
9 lioz 3
10 amit 2
11 ben 2
12 eran 1
我需要在一个查询中选择每行group_id
的2行,结果如下:
ID name group_id
== == ==
1 haim 1
3 alon 1
2 gil 2
6 adi 2
5 shai 3
7 itay 3
非常重要的是,它也将按group_id
排序。
谢谢!
答案 0 :(得分:2)
SELECT id ,
name,
parent_id
FROM ( SELECT id ,
name ,
parent_id,
CASE
WHEN @parent_id = parent_id
THEN @rownum := @rownum + 1
ELSE @rownum := 1
END AS rn,
@parent_id := parent_id
FROM (SELECT 1 as ID, 'haim' as NAME, 1 as parent_id
UNION ALL SELECT 2, 'gil', 2
UNION ALL SELECT 3, 'alon', 1
UNION ALL SELECT 4, 'idan', 1
UNION ALL SELECT 5, 'shai', 3
UNION ALL SELECT 6, 'adi', 2
UNION ALL SELECT 7, 'itay', 3
UNION ALL SELECT 8, 'aviram', 1
UNION ALL SELECT 9, 'lioz', 3
UNION ALL SELECT 10, 'amit', 2
UNION ALL SELECT 11, 'ben', 2
UNION ALL SELECT 12, 'eran', 1
)
YourTable
JOIN
(SELECT @rownum := 0,
@parent_id := NULL) r
ORDER BY parent_id
)
x
WHERE rn<=2
答案 1 :(得分:1)
最具适应性的方法是考虑变量:
set @rank:=0;
set @prev:=0;
select ID,name,group_id from
( select ID,name,group_id,@rank:=if(group_id=@prev,@rank+1,1) as rank,@prev:=group_id as dump from
( select ID,name,group_id from categories order by group_id asc) A
) A where rank<=2;
这样,您就不再依赖于每个group_id需要显示的行数。
方法是:
干杯
纪尧姆
答案 2 :(得分:0)
可能有几种方法可以实现这一点,但我会做两个查询,并使用UNION将它们合并在一起。
这样的事情:
(SELECT .... WHERE ID=GROUP_ID)
UNION
(SELECT .... GROUP BY GROUP_ID)
ORDER BY ID;
答案 3 :(得分:0)
我考虑了每个group_id在表格中找到的第一个和第二个ID。
SELECT ID, NAME, GROUP_ID
FROM MYTABLE WHERE ID IN (
SELECT MIN(ID)
FROM MYTABLE
GROUP BY GROUP_ID)
UNION ALL
SELECT ID, NAME, GROUP_ID
FROM MYTABLE WHERE ID IN (
SELECT MIN(ID)
FROM MYTABLE
WHERE ID NOT IN (
SELECT MIN(ID)
FROM MYTABLE
GROUP BY GROUP_ID
)
GROUP BY GROUP_ID)
ORDER BY GROUP_ID