我有两张桌子 A 和 B 。我的查询是 -
Select A.item, B.description, B.brand from A inner Join B on A.id=B.a_id where B.brand_id=1 limit 0,3
UNION
Select A.item, B.description, B.brand from A inner Join B on A.id=B.a_id where B.brand_id=2 limit 0,3
UNION
Select A.item, B.description, B.brand from A inner Join B on A.id=B.a_id where B.brand_id=3 limit 0,3
输出类似于 -
item description brand
1001 item1 brand1
1002 item2 brand1
1003 item3 brand1
1004 item4 brand2
1005 item5 brand2
1006 item6 brand2
1007 item7 brand3
1008 item8 brand3
1009 item9 brand3
现在我的要求是将记录提取为 -
item description brand
1001 item1 brand1
1004 item4 brand2
1007 item7 brand3
1002 item2 brand1
1005 item5 brand2
1008 item8 brand3
1003 item3 brand1
1006 item6 brand2
1009 item9 brand3
任何建议:(
答案 0 :(得分:3)
如果你想要一个纯粹的SQL答案,那么甲骨文RANK OVER PARTITION的以下MySQL解决方案加上内联视图和一些订购应该适用于你拥有的许多品牌:
select item,description,brand
from
(select A.item, B.description, B.brand,
case B.brand
when @curBrand
then @curRow := @curRow + 1
else @curRow := 1 and @curBrand := B.brand END
as rank
from A inner join B on A.id=B.a_id
join (select @curRow := 0, @curBrand := '') r
) t
order by t.rank,t.brand;
享受!