我在mysql中有以下表格:
+ + +
id | state | phone | files
+------------------------------------+
1 | on | 123123 | file1
2 | on | 124423 | file2
3 | off | 123455 | file1
4 | off | 128455 | file3
5 | on | 323132 | file3
6 | off | 124454 | file4
| | |
| | |
| | |
+ + +
我想选择谁有file1,并根据我检查状态,如果有关闭状态我选择电话号码如果没有任何关闭状态我选择第一个拥有表格中的file1。
在下次sql查询执行时,执行相同的过程,如果没有关闭状态,则返回下一个有文件1而不是前一个人的电话号码。我怎么能这样做?
答案 0 :(得分:0)
SELECT t.id
, t.state
, t.phone
, t.file
FROM mytable t
WHERE t.file = 'file1'
ORDER BY t.file, t.state, t.id
LIMIT 1
答案 1 :(得分:0)
您的陈述应该类似于
select phone from mytable
where file = 'file1'
and state = 'on'
and id > :last_id /* you'll need to provide the previously popped id as a variable */
order by id asc
limit 1;
对于PostgresSQL中的工作示例:
\set last_id 0
select phone from ( values
( 1, 'on', 123123, 'file1' ),
( 2, 'on', 124423, 'file2' ),
( 3, 'off', 123455, 'file1' ),
( 4, 'off', 128455, 'file3' ),
( 5, 'on', 323132, 'file3' ),
( 6, 'off', 124454, 'file4' )
) x ( id, state, phone, file)
where file = 'file1'
and state = 'on'
and id > :last_id
order by id asc
limit 1 ;