简体   繁体   English

从多个表中获取数据

[英]Fetching data from multiple tables

I have table 1 with columns我有带列的表 1

  • userid
  • deptname
  • deptid
  • working_in
  • joining_date
  • profession

Table 2 has columns表 2 有列

  • userid
  • salary
  • doj
  • user_mail

And table 3 contains表 3 包含

  • userid
  • deptname
  • deptid
  • salary

Both Table 1 and Table 2 contain some rows.表 1 和表 2 都包含一些行。 Table 3 contains no rows.表 3 不包含任何行。

The values of table 3 will be the combination of values from table 1 and table 2.表 3 的值将是表 1 和表 2 中值的组合。

How do I update table 3 by fetching only the details userid , deptname , deptid , salary required from table 1 and table 2?如何通过仅获取表 1 和表 2 所需的详细信息useriddeptnamedeptidsalary来更新表 3?

select t1.userid, t1.deptname, t1.deptid, t2.salary from table1 t1
join table2 t2
on t1.userid=t2.userid

That way you can, in a single query, get the details from both tables.这样,您可以在单个查询中从两个表中获取详细信息。 Notice that I used the a join according to the "userid" column.请注意,我根据“userid”列使用了连接。 That way the "salary" will be of the same user (assuming "userid" is a shared PK).这样,“薪水”将属于同一用户(假设“userid”是共享 PK)。

EDIT: In the example code above you don't insert anything.编辑:在上面的示例代码中,您没有插入任何内容。 There is only a SELECT statement.只有一个 SELECT 语句。 That means, you're only extracting the relevant data from both table1 and table2.这意味着,您只是从 table1 和 table2 中提取相关数据。 In order to put the data inside of table3 you need an INSERT stetment.为了将数据放入 table3,您需要一个 INSERT 语句。 You can look it up here http://www.techonthenet.com/oracle/insert.php , And it should end up something like :你可以在这里查看它http://www.techonthenet.com/oracle/insert.php ,它最终应该是这样的:

INSERT INTO table3 
(userid, deptname, deptid, salary)
VALUES (select t1.userid, t1.deptname, t1.deptid, t2.salary from table1 t1
join table2 t2
on t1.userid=t2.userid)

Assuming that假如说

  1. your "Table 1" is named table_1 ,您的“表 1”被命名为table_1
  2. your "Table 2" is named table_2 ,您的“表 2”被命名为table_2
  3. your "Table 3" is named table_3 ,你的“表 3”被命名为table_3
  4. your "combination of values" is a join between table 1 and table 2 on the userid column, and您的“值组合”是表 1 和表 2 在userid列上的连接,并且
  5. your "I update table 3" means you want to store the "combination of values" into your table 3,您的“我更新表 3”意味着您要将“值组合”存储到表 3 中,

then your query would be:那么您的查询将是:

insert into table_3 (userid, deptname, deptid, salary)
select userid, T1.deptname, T1.deptid, T2.salary
from table_1 T1
    join table_2 T2 using (userid)
;

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

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