2016-06-17 145 views
0

我有2個表我選擇並計數比較項形式2個表,也比較後我需要計算其他表中有多少項包含。將結果與其他表mysql比較

select 
    results.userid, 
    results.amount, 
    results.type, 
    results.counting 
from 
    (SELECT 
     userid, amount, code, count(*) as counting 
    FROM 
     user_buys 
    join star ON (amount >= min_amount) 
    group by type 
    HAVING amount >= 1000) as results 

與見下表

userid |amount  
---------------------- 
    1  | 1000   
    2  | 2000 
    3  | 5500  
    4  | 8200  
    5  | 200  
    6  | 1500 
    7  | 800 

我需要與其他表

min_compare| min_amount | type 
----------------------------------- 
    2   | 1000  | 1star 
    2   | 2000  | 2star 
    3   | 5000  | 3star 
    4   | 8000  | 4star 
    5   | 9000  | 5star 
    6   | 10000  | 6star 
    7   | 11000  | 7star 

,因爲我們必須同步

5 item larger 1000 it contain => 1star 
3 item larger 2000 it contain => 2star 
2 item larger 5000 it contain => 3star 
1 item larger 8000 it contain => 4star 

我預期的結果

rankin 
-------- 
    1star   
    2star 
    3star 
    4star 

我還有一個問題,數開始計數涉及到min_compare,如果我添加了新買的11000就必須有數量少7來計算7star

+0

您的預期結果是什麼? – Blank

+0

我需要向所有用戶顯示所有金額的最小明星,以及我更新我的問題並添加新的表結果。 –

回答

0

試試這個;)

select 
    star.type, star.min_amount, t.cnt, t.userids 
from star 
inner join (
    select t1.type, count(t2.userid) as cnt, group_concat(t2.userid order by t2.userid) as userids 
    from star t1 
    inner join user_buys t2 on t1.min_amount <= t2.amount 
    group by t1.type 
) t on t.type = star.type 
order by star.type 

SQLFiddle DEMO HERE

+0

謝謝。工作很好:) –

+0

親愛的雷諾我有另一個問題,請閱讀結束我的問題,我更新它 –

+0

@VahidAlvandi如果您有另一個問題,請再次提問。到目前爲止,這個查詢可以做到這一點,不是嗎? – Blank

0
select 
    star.type, star.min_amount, t.cnt, t.userids 
from star 
inner join (
    select t1.type, t1.min_compare, count(t2.userid) as cnt, group_concat(t2.userid order by t2.userid) as userids 
    from star t1 
    inner join user_buys t2 on t1.min_amount < t2.amount 
    group by t1.type 
    HAVING cnt >= t1.min_compare 
) t on t.type = star.type 
order by star.type