如何在IN子句中查询多个字段?

huangapple go评论77阅读模式
英文:

How to query with multiple fields in IN clause?

问题

我想查询一个具有多个组合字段的表格,在IN子句中使用。

示例:查找所有包含“john doe”和“marc smith”的记录,但忽略所有其他人。

SELECT * FROM persons 
WHERE firstname IN ('john', 'marc')
   AND lastname IN ('doe', 'smith');

但我不想找到例如jane;doe。但如何在IN子句中组合多个列?

英文:

I want to query a table with multiple combined fields in an IN clause.

Example: find all records with "john doe" and "marc smith", but ignore all other persons..

SELECT * FROM persons 
WHERE firstname IN ('john', 'marc')
   AND lastname IN ('doe', 'smith');

But I don't want to find jane;doe for example. But how can I combine multiple columns inside the IN clause?

答案1

得分: 1

我发现 MySQL 原生支持此功能:

SELECT * FROM persons WHERE (firstname, lastname) IN (('john', 'doe'), ('marc', 'smith'));
英文:

I discovered mysql supports this out of the box:

SELECT * FROM persons WHERE (firstname, lastname) IN (('john', 'doe'), ('marc', 'smith'));

答案2

得分: 1

你可以考虑创建一个包含你感兴趣的名字和姓氏组合的查找表。然后查询类似于以下内容:

SELECT persons.*
FROM persons
JOIN my_lookup
ON persons.firstname = my_lookup.firstname
AND persons.lastname = my_lookup.lastname;

为了加速这个过程,我会在查找表中的名字/姓氏上创建一个唯一索引。

英文:

You might consider creating a sort of lookup table that contains the first- and lastname combinations you're interested in.
Then query something like this:

SELECT persons.*
FROM   persons
JOIN   my_lookup
  ON   persons.firstname = my_lookup.firstname
 AND   persons.lastname = my_lookup.lastname;

In order to speed up the process, I would create a unique index on the first/lastname within that lookup table.

答案3

得分: 0

你可以直接使用上面的连接函数,这将帮助你消除不同的名字和姓氏组合。
希望这对你有帮助!!!

select * from persons where CONCAT(first_name, ' ', last_name) in ('john doe', 'marc smith');
英文:

You can just use the above concat function which would help you to eliminate different combination of name and surname.
Hope this helps !!!!

 select * from persons where CONCAT(first_name,' ',last_name) in ("john doe","marc smith");

huangapple
  • 本文由 发表于 2023年6月27日 19:09:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定