'Only those whoe have an offer or service(Not Null Value)
I have 3 tables like this
1st table:person
| PID | MOBILE |
|---|---|
| 1 | 123 |
| 2 | 234 |
| 3 | 345 |
| 4 | 456 |
2nd table: offer
| PID | of_id | of_name |
|---|---|---|
| 1 | 11 | offer 1 |
| 3 | 12 | offer 2 |
| 3 | 13 | offer 3 |
3td table: service
| PID | ser_id | ser_name |
|---|---|---|
| 2 | 10 | ser 2 |
| 1 | 11 | ser 1 |
I want table like this:
| PID | mobile | of_name | ser_name |
|---|---|---|---|
| 1 | 123 | offer 1 | ser 1 |
| 2 | 234 | ser 2 | |
| 3 | 345 | offer 3 | |
| 3 | 34 | offer 3 |
i tried:
select distinct p.pid,p.mobile,o.of_name,s.ser_name
from person p
left join (select pid,of_name from offer) o on p.pid = o.pid
left join (select pid,ser_name from service) s on p.pid = s.pid
but i got:
| PID | mobile | of_name | ser_name |
|---|---|---|---|
| 1 | 123 | offer 1 | ser 1 |
| 2 | 234 | ser 2 | |
| 3 | 345 | offer 3 | |
| 3 | 34 | offer 3 | |
| 4 | 456 |
So, My table should only include those who have an offer or service.
Solution 1:[1]
try like below
with cte as(select p.pid,p.mbl,
o.name as offername,s.name as service_name from person p
left join offer o on p.pid=o.pid
left join service s on p.pid=s.pid
) select pid,mbl,offername,service_name
from cte where pid in (select pid from offer
union
select pid from service)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zaynul Abadin Tuhin |
