Mysql SELECT值比较?

时间:2016-07-12 19:35:42

标签: mysql

像这样的表:

-----------------------------
id    pid    key    value
-----------------------------
1      3    all     120
2      3    today   180
3      9    all     200
4      9    today   150
5      9    others   0
-----------------------------

如何

select * from table if all(120) < today(180) and if they have same pid(3)

我希望结果应该是:

---------------------------
id    pid    key    value
---------------------------
1      3     all    120
2      3    today   180

2 个答案:

答案 0 :(得分:0)

假设您希望所有条目与另一个条目全部&lt;今天存在相同的pid

select t from table t where exists( 
    select * from table t2 where t.all < t2.today and t.pid = t2.pid
)

答案 1 :(得分:0)

试试这个:

select t1.*
from yourtable t1
inner join (
    select *
    from yourtable
    group by pid
    having sum(if(`key` = 'all', `value`, 0)) < sum(if(`key` = 'today', `value`, 0))
) t2 on t1.pid = t2.pid

SQLFiddle Demo