在表foo中有两个字符串列a和b。

select a, b from foo返回值a和b。但是,a和b的串联不起作用。我试着:

select a || b from foo

and

select  a||', '||b from foo

从注释更新:两列都是类型字符(2)。


当前回答

问题在于值中的空值;那么,连接对null无效。解决方法如下:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

其他回答

问题在于值中的空值;那么,连接对null无效。解决方法如下:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

最好使用PostgreSQL中的CONCAT函数进行连接

select CONCAT(first_name,last_name) from person where pid = 136

如果使用column_a || ' ' || column_b对2列进行连接,如果column_a或column_b中的任何值为null,则查询将返回空值。 这可能不是在所有情况下都可取。所以不是这样

||

use

CONCAT

如果它们中的任何一个有值,它将返回相关的值

PHP的Laravel框架, 我使用搜索first_name, last_name字段考虑像全名搜索

使用||符号或concat_ws(), concat()方法

$names = str_replace(" ", "", $searchKey);                               
$customers = Customer::where('organization_id',$this->user->organization_id)
             ->where(function ($q) use ($searchKey, $names) {
                 $q->orWhere('phone_number', 'ilike', "%{$searchKey}%"); 
                 $q->orWhere('email', 'ilike', "%{$searchKey}%");
                 $q->orWhereRaw('(first_name || last_name) LIKE ? ', '%' . $names. '%');
    })->orderBy('created_at','desc')->paginate(20);

这招奏效了!!

例如,如果有一个员工表,它由如下列组成:

employee_number,f_name,l_name,email_id,phone_number 

如果我们想连接f_name + l_name作为名称。

SELECT employee_number,f_name ::TEXT ||','|| l_name::TEXT  AS "NAME",email_id,phone_number,designation FROM EMPLOYEE;

CONCAT函数有时不适用于较旧的postgreSQL版本

看看我不使用CONCAT是如何解决问题的

 u.first_name || ' ' || u.last_name as user,

或者你也可以用

 "first_name" || ' ' || "last_name" as user,

在第二种情况下,我使用双引号first_name和last_name

希望这对你有用,谢谢