2015-09-26 49 views
0

我有一个两列的表:first_namelast_name。在应用程序中,用户可以看到全名(例如,名字+姓氏)。如何组合两列来应用过滤器?

例子:

first_name last_name 
bat   man 
Barack  Obama 

在应用如果“蝙蝠人”的用户搜索,他没有得到结果。
那么,我该如何过滤两列?

我当前的SQL:

select * 
from people 
where first_name ilike 'bat man' 
or last_name ilike 'bat man' 

回答

2

您正在寻找的字符串连接运算符,||

SELECT * 
    FROM people 
WHERE (first_name || ' ' || last_name) ILIKE 'bat man' 

§9.4 "String Functions and Operators" in PostgreSQL 9.4.4 Documentation

+0

这样做的麻烦是它使得查询不可操作,所以每个查询都必须扫描整个表。幸运的是,Postgresql有一个可以创建的函数索引:*在people上创建索引people_full_name(first_name ||''|| last_name); *。从那时起,“where people_full_name ilike'bat man'”将使用索引。 – TommCatt

+0

@TommCatt:对不起,但你的前提是错误的。如果你在'first_name ||上创建一个函数索引''|| last_name“,那么PostgreSQL足够聪明,可以将它用于依赖于该表达式的查询。 (请参阅http://www.postgresql.org/docs/9.4/static/indexes-expressional.html,它足够有趣 - 使用这个确切的例子。)这个查询不适合索引的原因,如果你想提出这一点,是'ilike'。 – ruakh

+0

你说得对。我对Postgresql有足够的了解,知道函数索引(很多数据库都有),但没有研究'ilike'的细节。因此,在'lower(first_name ||''|| last_name)'上创建索引并将表达式更改为“where people_full_name like lower('bat man')”(甚至“where people_full_name = lower('bat man')”)因为没有使用通配符。当然,'蝙蝠侠'不会像我们的例子那样被硬编码。 – TommCatt