There are Three tables T1 and T2 and T3
T3 stores person details T1 stores primary phone number of person, T2 stores non primary phone number of persons.
T1
Personid | Primaryphone | dateload |
---|---|---|
1 | 1001 | 02/08/21 |
2 | 1002 | 03/07/21 |
4 | 1004 | 04/08/20 |
5 | 1005 | 08/09/20 |
T2
Personid | NonPrimphone | dateload |
---|---|---|
1 | 1011 | 12/03/21 |
3 | 1003 | 20/02/21 |
4 | 1024 | 30/12/21 |
6 | 1006 | 08/08/20 |
3 | 1007 | 04/04/21 |
3 | 1008 | 21/08/21 |
T3
Per_numb | person_id |
---|---|
501 | 1 |
502 | 2 |
503 | 3 |
504 | 4 |
505 | 5 |
506 | 6 |
What i want is, select all personumber from T3 and thier phone number , the criteria is , if the person is having primary phone number select that, if not having primary phone number select phone number from non primary table having latest dateload.
i.e
O/p
Per_numb | phonenumber |
---|---|
501 | 1001 |
502 | 1002 |
503 | 1008 |
504 | 1004 |
505 | 1005 |
506 | 1006 |
I also want to join these three tables and not use sub queries as the sub query is making the execution slow.
Advertisement
Answer
One method uses coalesce()
:
select t3.*, coalesce( (select t1.primaryphone from t1 where t1.personid = t3.personid ), (select t2.phone from t2 where t2.personid = t3.personid order by t2.dateload desc fetch first 1 row only ) ) a_good_phone from t3;