Backwards LIKE Statements
Sometimes you need to think backwards.
Here was the problem. I needed to match up some IP address ranges to the company that owns them. Looking for a simple solution to the problem I came up with storing the IP address block patterns in the database as follows:
ip_pattern ---------------- 127.%.%.% 192.168.%.% 10.%.%.%
Any idea why I choose % as the wildcard?
That's right - it's the wildcard operator in SQL for the LIKE statement.
So now when I have have an IP address 192.168.1.1, I can do what I like to call a backwards LIKE query:
SELECT company, ip_pattern FROM company_blocks WHERE '192.168.1.1' LIKE ip_pattern
This works on SQL Server and MySQL, and I would think it should work fine on any database server.
Tweet
Related Entries
- INFORMATION_SCHEMA Support in MySQL, PostgreSQL - February 18, 2008
- SQL to Select a random row from a database table - September 14, 2005
- SQL Reserved Key Words Checker Tool - March 28, 2005
- Top 10 Reserved SQL Keywords - October 28, 2008
- SQL Case Statement - October 15, 2008
Trackbacks
Comments
D
http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html
Ronald http://blog.arabx.com.au
and with SELECT TOP 1 @Destination = DestinationName FROM [UM-SHARE].dbo.tblDestinationCode WHERE RTRIM(LTRIM(@Number)) like DialCode + '%' ORDER BY LEN(DialCode) DESC
one can find the destination (country) for a specific number.
# 127.%.%.% # 192.168.%.% # 10.%.%.%
INSERT INTO company_blocks (company, ip_from, ip_to) VALUES(INET_ATON('127.0.0.1'), INET_ATON('127.255.255.255')), (INET_ATON('192.168.0.0'), INET_ATON('192.168.255.255')), (INET_ATON('10.0.0.0'), INET_ATON(10.255.255.255'));
SELECT company, INET_NTOA(ip_from), INET_NTOA(ip_to) FROM company_blocks WHERE ip_from <= INET_ATON('192.168.1.1') AND ip_to >= INET_ATON('192.168.1.1') LIMIT 1;
(Haven't tested this but) this should make efficient use of a multi column index [ip_from, ip_to].
SELECT TOP 1 @Destination = DestinationName FROM [UM-SHARE].dbo.tblDestinationCode WHERE DialCode <= RTRIM(LTRIM(@Number)) ORDER BY DialCode DESC;
DialCode must be a text field or your rdbms must do automatic type casting.
Post a Comment
Recent Entries
- Writing Secure CFML cfObjective 2013 Slides
- Upgrading to Java 7 on Linux
- J2EE Sessions in CF10 Uses Secure Cookies
- Learn about ColdFusion Security at cfObjective 2013
- Session Loss and Session Fixation in ColdFusion
- FuseGuard 2.3 Released
- CKEditor Spell Checker Plugin
- Adobe Says Go Ahead and Upgrade your ColdFusion JVM


add to del.icio.us


