2016-11-30 59 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 | 
+--------------+--------------+-----------------+