用于选择IP和名称范围的SQL查询

时间:2014-03-01 12:14:00

标签: sql sql-server

如何选择具有给定IP和名称“admin”的记录?

我有这个用于IP,但觉得这不是分组范围的最佳方式。如评论中所述,我想选择可能具有IP的“名称”:“x”或“y”或“z”

SELECT DISTINCT (name) AS name
FROM  `log` 
WHERE  `ip` =  '08.88.16.98'
OR  `ip` =  '03.12.27.226'
OR  `ip` =  '03.23.113.116'
OR  `ip` =  '06.204.69.183'
OR  `ip` =  '07.31.0.209'

2 个答案:

答案 0 :(得分:1)

使用IN子句代替OR语句:

SELECT DISTINCT (name) AS name
FROM  log 
WHERE ip
IN ('08.88.16.98','03.12.27.226','03.23.113.116','06.204.69.183','07.31.0.209')
AND name = 'admin';
  

IN运算符允许您在WHERE中指定多个值   子句。

正如旁注,如果要排除值,可以在NOT子句之前使用IN子句,例如:

NOT IN ('08.88.16.98','03.12.24.254','03.23.113.189');

请在此处详细了解:IN (Transact-SQL)

答案 1 :(得分:0)

您可以为所需的IP地址添加新表。给它ips。然后加入两个表:

SELECT DISTINCT (name) AS name
FROM  `log` 
JOIN `ips` ON (log.ip = ips.ip);