根据sql count

时间:2016-10-24 18:43:49

标签: mysql sql if-statement

我想基于第一个COUNT sql查询运行一个SQL查询:

SET @result = "SELECT count(*) FROM ip_addresses WHERE id > (SELECT id FROM ip_addresses WHERE in_use=1) ORDER BY id LIMIT 1"
CASE WHEN (@result > 0)
    THEN SELECT * FROM ip_addresses WHERE id > (SELECT id FROM ip_addresses WHERE in_use=1) ORDER BY id LIMIT 1
    ELSE SELECT * FROM ip_addresses WHERE in_use!=1 ORDER BY id LIMIT 1
END

基本上我想要做的是,我希望得到in_use=0的下一条记录WHERE in_use=1。如果in_use=1记录是表的最后一条记录,它应该获得带有in_use=0的表的第一条记录。 更多解释: 如果ip_addresses表有以下数据

 id|     ip     |in_use
 1 | 192.168.1.5|1
 2 | 89.58.1.2  |0
 3 | 58.98.58.6 |0

现在它应该返回第二条记录。

如果ip_addresses表有以下数据

 id|     ip     |in_use
 1 | 192.168.1.5|0
 2 | 89.58.1.2  |0
 3 | 58.98.58.6 |1

现在它应该返回第一条记录。

3 个答案:

答案 0 :(得分:1)

你有几个问题。最重要的是控制流逻辑只允许在编程块中使用。

但是,您可以通过单个查询完成所需的操作。例如:

(SELECT ia.*, 1 as priority
 FROM ip_addresses ia
 WHERE id > (SELECT id FROM ip_addresses WHERE in_use = 1)
 ORDER BY id
 LIMIT 1
)
UNION ALL
(SELECT ia.*, 2 as priority
 FROM ip_addresses ia
 WHERE in_use <> 1
 ORDER BY id
 LIMIT 1
)
ORDER BY priority
LIMIT 1

答案 1 :(得分:0)

以xQbert的答案为基础:

select  IP
from   ( select case when id >
        ( select min( ID )
          from    IP_ADDRESES
          where   in_use = 1 ) 
        then ID - ( select max( ID ) from IP_ADDRESES )
        else id 
        end case
    from IP_ADDRESES as deflated_id,
    ip )
order by deflated_id asc 
top 1

答案 2 :(得分:0)

SELECT A.IP 
  FROM  IP_Addresses A, 
       ( SELECT min(ID) mid
           FROM IP_ADDRESES 
          WHERE in_use= 0
        ) B
WHERE A.id = B.mid;