Mysql Where … In … AND where … in … should only match on same index

梦想与她 提交于 2019-12-10 04:10:42

问题


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

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