简体   繁体   English

在mysql和php中合并两个表的更有效方法?

[英]A more efficient way to merge two tables in mysql and php?

I have two tables that contain similar information. 我有两个包含相似信息的表。 As a minimal example say I have the following: 举一个最小的例子,我有以下几点:

table1  id|date|info1
table2  id|date|info2

I want to merge these two tables into one such that it becomes 我想将这两个表合并为一个

table3 id|date|info1|info2

I tried the following: 我尝试了以下方法:

SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date

then loop through this selection and update accordingly. 然后遍历此选择并进行相应更新。

It works, but is very slow. 它可以工作,但是非常慢。 I was wondering whether there was a better way to do this. 我想知道是否有更好的方法可以做到这一点。

You can use CTAS (Create Table As Select) like this: 您可以像这样使用CTAS(将表创建为选定对象):

CREATE TABLE YourMergedTable AS
SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date

MySQL will detect the types of the fields that result from the query, and make a table structure accordingly. MySQL将检测查询产生的字段类型,并相应地建立表结构。

If you already have a table, or you want to create it explicitly for any other reason, you can still insert records like that: 如果您已经有一个表,或者出于任何其他原因想要显式创建它,则仍可以插入如下记录:

INSERT INTO YourMergedTable(ID, Date, Info1, Info2) /* These are the fieldnames in the  table */
SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date

This will produce the result as id|date|info1|info2 这将产生结果为id | date | info1 | info2

    SELECT id, date, info1 AS info1, NULL AS info2 FROM table1
    UNION
    SELECT id, date, NULL AS info1, info2 AS info2 FROM table2

To insert the results into a table3 you can do 要将结果插入到table3中,您可以执行

    INSERT INTO table3
    SELECT id, date, info1 AS info1, NULL AS info2 FROM table1
    UNION
    SELECT id, date, NULL AS info1, info2 AS info2 FROM table2

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

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