问题
I have the query:
SELECT * FROM `users`
WHERE (`firstname` LIKE 'Luke' AND `lastname` LIKE 'Skywalker') OR
(`firstname` LIKE 'Foo' AND `lastname` LIKE 'Bar') OR
(`firstname` LIKE 'Tom' AND `lastname` LIKE 'Turner');
But i would like to make it a bit more readable by using a where ... in ... I tried
SELECT * FROM users
WHERE `firstname`
IN ('Luke','Foo','Tom') AND `lastname` IN ('Skywalker','Bar','Turner');
But unfortunately this will also match "Tom Skywalker"
, "Foo Turner"
and all mixes you can think off.
I have to select on first and lastname (perhaps more fields like DOB) since i am getting data from an external API and i have to check if those names are in our system.
回答1:
SELECT *
FROM users
WHERE (firstname, lastname)
IN ( ('Luke', 'Skywalker')
, ('Foo' , 'Bar')
, ('Tom' , 'Turner')
)
;
回答2:
Using LIKE
operator without wildcards doesn't make much sense. I think you should use =
, particularly if you have to check if those names are in our system
.
SELECT * FROM users
WHERE (firstname = 'Luke' AND lastname = 'Skywalker') OR
(firstname = 'Foo' AND lastname = 'Bar') OR
(firstname = 'Tom' AND lastname = 'Turner')
If you use an IN
operator, as you said, will match different combinations. I think the previous example should be the fastest way to compare them.
回答3:
You can combine them with concat
:
WHERE concat(`firstname`,'-',`lastname`)
IN ('Luke-Skywalker', 'Foo-Bar', 'Tom-Turner');
来源:https://stackoverflow.com/questions/10111153/mysql-where-in-and-where-in-should-only-match-on-same-index