将结果与其他表mysql进行比较

时间:2016-06-17 07:02:50

标签: mysql compare

我有2个表我选择并计算比较项表2表,也比较后我需要计算其他表中包含多少项。

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来计算7星

2 个答案:

答案 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

答案 1 :(得分: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