2016-11-30 272 views
0

我可能没有正确地获取我的条款,因此无法在Web上找到答案。Mysql在Select语句中为列名添加前缀

我有2代表这样

customer_db - Customer Data 
CustomerID CustomerName  CustomerContact 
1    John    1234 
2    Anna    5678 
3    Angel   2468 

customer_channel - Chat Channel Name 
ChannelName   OnlineStatus 
private-customer-1  YES 
private-customer-2  NO 

所以通常我会做这样的事情

Select a.OnlineStatus, b.CustomerName, b.CustomerContact FROM customer_db a, 
customer_channel b WHERE a.CustomerID = b.ChannelName 

这里的“私人客户为”前缀是存在的,所以我不能做匹配。

我试着添加一个前缀,但它不起作用。 如何选择在WHERE语句中向列名添加“文本前缀”的表?

Select a.OnlineStatus, b.CustomerName, b.CustomerContact FROM customer_db a, 
customer_channel b WHERE a.CustomerID = 'private-customer-'+b.ChannelName 

回答

1

使用concat功能,逗号(,),其子查询结果做JOIN是一个古老的方式,尽量使用join

SELECT 
    a.OnlineStatus, 
    b.CustomerName, 
    b.CustomerContact 
FROM customer_db a 
JOIN customer_channel b 
ON a.CustomerID = concat('private-customer-', b.ChannelName) 
0

在WHERE语句

添加一个“文本前缀”列名不,你不能这样做,除非你正在成为一个动态查询(预处理语句)。前缀或后缀只能用于列名或别名的别名。

(OR),您可以使用子查询,并与像

Select a.OnlineStatus, 
b.CustomerName, 
b.CustomerContact 
FROM customer_db a JOIN (select CustomerName, CustomerContact, 
'private-customer-'+ ChannelName as channelName 
from customer_channel) b 
ON a.CustomerID = b.channelName; 
0

尝试这种使用Concat函数..

Select a.OnlineStatus, 
     b.CustomerName, 
     b.CustomerContact 
    FROM customer_db a, 
     customer_channel b 
    WHERE a.CustomerID = concat('private-customer-', b.ChannelName) 
0

你可以使用这种替代或子 例如给出

drop table if exists a; 
create table a(CustomerID int, CustomerName varchar(5), CustomerContact int); 
insert into a values 
(1,    'John' ,   1234), 
(2,    'Anna' ,   5678), 
(3,    'Angel',   2468); 

drop table if exists b; 
create table b (ChannelName varchar(20),   OnlineStatus varchar(3)); 
insert into b values 
('private-customer-1' , 'YES'), 
('private-customer-2' , 'NO'); 

Select b.OnlineStatus, a.CustomerName, a.CustomerContact 
FROM a 
join b on a.CustomerID = replace(b.ChannelName,'private-customer-',''); 

Select b.OnlineStatus, a.CustomerName, a.CustomerContact 
FROM a 
join b on a.CustomerID = substring(b.ChannelName,18,length(b.channelname) -17) 

两个查询导致

+--------------+--------------+-----------------+ 
| OnlineStatus | CustomerName | CustomerContact | 
+--------------+--------------+-----------------+ 
| YES   | John   |   1234 | 
| NO   | Anna   |   5678 | 
+--------------+--------------+-----------------+