patternsqlModerate
Find if any of the rows partially match a string
Viewed 0 times
rowstheanymatchpartiallyfindstring
Problem
I want to see if a table contains any sub-string of a given string.
Let's say I have a string
In database I have:
I need to make a query that will return "domain.com" as it is a substring of "somedomain.com".
I don't know if this is even possible in MySQL.
Let's say I have a string
somedomain.comIn database I have:
blabladomain.com
testdomain.com
domain.comI need to make a query that will return "domain.com" as it is a substring of "somedomain.com".
I don't know if this is even possible in MySQL.
CREATE TABLE `site_core_antispam_banned_domain` (
`domain_id` int(11) NOT NULL AUTO_INCREMENT,
`domain_name` varchar(255) NOT NULL,
PRIMARY KEY (`domain_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;Solution
You can use
The above will look for domains that match any part of a given string. If you specifically wanted domains matching the right side of the string (for instance, if the domain to match against was
Note: there is no performance guarantee with these queries. The execution plan will likely include either a full index scan - if there is an index on
LOCATE() – as in the other answer – or LIKE:SELECT *
FROM site_core_antispam_banned_domain
WHERE 'subdomain.com' LIKE CONCAT('%', domain_name, '%') ;The above will look for domains that match any part of a given string. If you specifically wanted domains matching the right side of the string (for instance, if the domain to match against was
somedomain.com.ro and you were only interested in *.com.ro results), you could make the pattern more specific:SELECT *
FROM site_core_antispam_banned_domain
WHERE 'subdomain.com' LIKE CONCAT('%', domain_name) ;Note: there is no performance guarantee with these queries. The execution plan will likely include either a full index scan - if there is an index on
(domain_name) - or a full table scan.Code Snippets
SELECT *
FROM site_core_antispam_banned_domain
WHERE 'subdomain.com' LIKE CONCAT('%', domain_name, '%') ;SELECT *
FROM site_core_antispam_banned_domain
WHERE 'subdomain.com' LIKE CONCAT('%', domain_name) ;Context
StackExchange Database Administrators Q#203206, answer score: 13
Revisions (0)
No revisions yet.