With SQL can you use a sub-query in a WHERE LIKE clause?

血红的双手。 提交于 2019-12-14 03:53:17

问题


I'm not even sure how to even phrase this as it sounds weird conceptually, but I'll give it a try. Basically I'm looking for a way to create a query that is essentially a WHERE IN LIKE SELECT statement.

As an example, if I wanted to find all user records with a hotmail.com email address, I could do something like:

SELECT UserEmail 
FROM Users 
WHERE (UserEmail LIKE '%hotmail.com')

But what if I wanted to use a subquery as the matching criteria? Something like this:

SELECT UserEmail 
FROM Users 
WHERE (UserEmail LIKE (SELECT '%'+ Domain FROM Domains))

Is that even possible? If so, what's the right syntax?


回答1:


You can try

SELECT  u.*
FROM    Users u INNER JOIN
        Domains d ON u.UserEmail LIKE '%'+ d.Domain

Or even try

SELECT  u.*
FROM    Users u
WHERE   EXISTS(SELECT 1 FROM Domains d WHERE u.UserEmail LIKE '%' + d.Domain)



回答2:


Although

SELECT  u.UserMail
FROM    Users u
WHERE   EXISTS(SELECT 1 FROM Domains d WHERE u.UserEmail LIKE '%' + d.Domain)

will give what you look for, please realise that like is expensive and that you could shave off a bit of time with (mysql dialect):

SELECT  u.UserMail
FROM    Users u
WHERE   SUBSTRING_INDEX(u.UserMail, '@', -1) IN (SELECT d.Domain FROM Domains)

or even

SELECT  u.UserMail
FROM    Users u
        INNER JOIN Domains d ON SUBSTRING_INDEX(u.UserMail, '@', -1) = d.Domain

(and that you could split e-mail into username and domain fields if this is a common operation in your database)

EDIT: I missed the MS SQL server tag. For that dialect

substring(UserMail, charindex('@', UserMail) + 1, len(UserMail) - charindex('@', UserMail) )

should outperform LIKE (because it will be performed once per row in Users and the you get to straight join, where the like approach will have to be performed for each value in Users on each row in Domains).

P.S. check my formulas for start and length in substring (it was Friday night yesterday).



来源:https://stackoverflow.com/questions/2528858/with-sql-can-you-use-a-sub-query-in-a-where-like-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!