简体   繁体   English

如何一次从两个表中获取数据

[英]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 . 有两个表具有相同的列,如namemobileaddressage
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. 现在,如果我在学生表中没有找到任何内容,那么我将从Teacher表中检索数据。

how to write this query ? 怎么写这个查询?

To get results from the two tables you would use UNION ALL. 要从两个表中获取结果,您将使用UNION ALL。 Here however you only want to access table Teacher when there are no matching rows in table Student. 但是,当表Student中没有匹配的行时,您只想访问表Teacher。 This is slightly more difficult. 这稍微困难一些。 You can still use UNION ALL, but need an EXISTS clause on your teacher query. 您仍然可以使用UNION ALL,但需要在教师查询中使用EXISTS子句。

select * from student
union all
select * from teacher where not exists (select * from student);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM