2013-02-15 36 views
0

我有兩個表AB。我的查詢是 -需要MySQL查詢來從數據庫中提取替代記錄

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 

和輸出是類似TO-

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組? – 2013-02-15 14:54:45

+0

是的,邁克爾你是對的,抱歉,如果我不清楚.. – Santosh 2013-02-15 14:56:15

+0

你使用什麼應用程序編程語言?也許我會把你擁有的所有行放入單個數組(或任何你喜歡的語言結構),然後修改數組的順序。要清楚的是,我只會在一個小的行集上做到這一點。如果你的生產行集比這個大得多,那麼在代碼中斬斷輸出可能不是最有效的。 – 2013-02-15 14:58:16

回答

3

如果您想要一個純粹的SQL答案,那麼下面的MySQL解決方案適用於Oracle的RANK OVER PARTITION,再加上一個inlin e查看和一些訂購應該工作,但你有很多品牌:

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; 

享受!

+0

我可以有你的查詢的MySQL版本。這是我的頭:( – Santosh 2013-02-15 16:45:23

+0

這是一個MySQL版本的查詢!在MySQL中給它一個。它不是一個Oracle查詢只是一個Oracle功能的MySQL版本.... – 2013-02-15 16:47:09

+0

感謝它的工作:) – Santosh 2013-02-16 14:48:55

相關問題