I have three tables customer1
, customer2
and product
as shown below:
Customer1 :
c_id --- c_name
----------------
1 --- anns
2 --- skja
3 --- kkjk
customer2 :
c_id --- c_name
----------------
11 --- sjhja
12 --- skkkkk
13 --- aaasss
product :
p_id --- c_id --- p_name
-------------------------
1 --- 1 --- pen
2 --- 2 --- card
3 --- 3 --- cell
4 --- 11 --- pot
5 --- 12 --- ice
6 --- 13 --- apple
I want to replace the value of c_id
in product
table with c_name
from customer1
and customer2
I am using below sql query :
SELECT c1.c_name or c2.c_name as customer_name, p.p_name from product p
left JOIN customer1 c1 on c1.c_id=p.c_id
left JOIN customer2 c2 on c2.c_id=p.c_id;
getting result :
c_name ----- p_name
---------------
null ----- pen
null ----- card
null ----- cell
null ----- pot
null ----- ice
null ----- apple
desired result :
c_name ----- p_name
----------------------
anns ----- pen
skja ----- card
kkjk ----- cell
sjhja ----- pot
skkkkk ----- ice
aaasss ----- apple
please help me out to get desired results.
SELECT coalesce(c1.c_name,c2.c_name) as cus_name, p.p_name product_name
from product p
JOIN customer1 c1
on c1.c_id=p.c_id
JOIN customer2 c2
on c2.c_id=p.c_id;
Try:
SELECT coalesce(c1.c_name,c2.c_name) as customer_name, p.p_name from product p
left JOIN customer1 c1 on c1.c_id=p.c_id
left JOIN customer2 c2 on c2.c_id=p.c_id;
Try this untested query:
SELECT ifnull (c1.c_name ,c2.c_name) as customer_name, p.p_name from product p
left JOIN customer1 c1 on c1.c_id=p.c_id
left JOIN customer2 c2 on c2.c_id=p.c_id;
this may help in your case
SELECT coalesce(k1.c_name,k2.c_name) as customer_name, j.p_name from product j
left JOIN customer1 k1 on k1.c_id=j.c_id
left JOIN customer2 k2 on k2.c_id=j.c_id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.