当前位置: 动力学知识库 > 问答 > 编程问答 >

sql - How to fetch data from two table in one go

问题描述:

I have a requirement where I have to fetch data from database table.

Condition is,

There are two tables with identical columns like name, mobile, address, age.

Ex. table names like Student and Teacher.

now if I don't find anything in student table then I will retrieve data from Teacher table.

how to write this query ?

网友答案:

To get results from the two tables you would use UNION ALL. Here however you only want to access table Teacher when there are no matching rows in table Student. This is slightly more difficult. You can still use UNION ALL, but need an EXISTS clause on your teacher query.

select * from student
union all
select * from teacher where not exists (select * from student);
分享给朋友:
您可能感兴趣的文章:
随机阅读: