简体   繁体   English

如何使用MYSQL将两个表中的记录合并为第三个

[英]How to merge records from two tables into third using MYSQL

I have 3 tables A, B, C 我有3张桌子A,B,C

Schema of all 3 tables is same as mentioned below: 所有3个表的模式与下面提到的相同:

1st A table: 第一张桌子:

cpid ,name, place 

2nd B table: 第二张B表:

connectorid,dob

3rd C table: 第3个C表:

ccpid cconnectorid 

Now both tables A and B have many records. 现在表A和B都有很多记录。 Now some of the records in A and B are with same id. 现在A和B中的一些记录具有相同的id。 Now I want to merge the records from A and B into Table C. Merge logic is as follows 现在我想将A和B中的记录合并到表C中。合并逻辑如下

1)If records with cpid = connectorid ,insert into table c.
2)C Table  ccpid is the foreignkey for A table cpid and cconnectorid is the foreignkey B table connectorid.
3)Using select query.

You can use select insert with an inner join 您可以使用带内连接的select插入

 insert into table_c
 select a.cpid, b.connectorid, a.place
 from table_b as b
 inner join table_a as a  on a.id = b.id

You can try this solution for your query: 您可以针对您的查询尝试此解决方案:

INSERT INTO `C`(`ccpid`, `cconnectorid`, `ccity`)
SELECT ta.`cpid`, ta.`cconnectorid`, tb.`place`
FROM `A`  as ta
  INNER JOIN `B` tb ON ta.`cpid` = tb.`cconnectorid` 

You just need join data from both tables? 您只需要从两个表中连接数据? This is simple JOIN function. 这是简单的JOIN功能。

SELECT *
    FROM Table_A
    INNER JOIN Table_B
    ON Table_A.cpid =Table_B.connectorid;

You can insert this select to your Table_C. 您可以将此选择插入Table_C。

Here is INNER JOIN, but I think you should take a look to JOINs, here are examples and you can read more about other JOINs. 这是INNER JOIN,但我认为你应该看看JOIN, 这里有例子,你可以阅读更多关于其他JOIN的信息。

INNER JOIN : Returns all rows when there is at least one match in BOTH tables LEFT JOIN : Return all rows from the left table, and the matched rows from the right table RIGHT JOIN : Return all rows from the right table, and the matched rows from the left table FULL JOIN : Return all rows when there is a match in ONE of the tables INNER JOIN :当BOTH表中至少有一个匹配时返回所有行LEFT JOIN :返回左表中的所有行,右表中匹配的行RIGHT JOIN :返回右表中的所有行和匹配的行从左表FULL JOIN :当其中一个表中存在匹配时返回所有行

use following query replace with your table names 使用以下查询替换您的表名

INSERT INTO CTABLE(ccpid,cconnectorid,ccity)
(SELECT A.cpid ,B.connectorid, A.place FROM 
TABLEA A INNER JOIN TABLEB B ON A.cpid = B.connectorid)

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

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