如何从数据库表中获取结果?

时间:2012-10-14 20:53:02

标签: mysql

我有3个表:phone,phones_state和state

电话:

+------------------+
| phone_id | model |
+----------+-------+
| 1        | mot   |
| 2        | sam   |
+----------+-------+

phones_state:

+---------------------+
| phone_id | state_id |
+----------+----------+
| 2        | 1        |
| 2        | 3        |
| 2        | 5        |
| 1        | 1        |
+----------+----------+

状态:

+------------------+
| state_id | name  |
+----------+-------+
| 1        | rec   |
| 2        | notre |
| 3        | res   |
| 4        | wait  |
| 5        | back  |
+----------+-------+

我希望所有处于状态1但未处于状态5的手机 我怎么能在mysql查询中做到这一点?

1 个答案:

答案 0 :(得分:2)

select p.phone_id
from phones p
inner join phones_state ps on ps.phone_id = p.phone_id
group by p.phone_id
having sum(ps.state_id = 1) >= 1 and sum(ps.state_id = 5) = 0