如何从另一个旧表创建新表

时间:2017-06-13 15:34:12

标签: mysql

我想从另一个旧表的某些列创建一个表。旧表中的每一列都有149行,但是当我创建新表时,结果表有1442行,这是错误的。

我的代码:

create table newenronss as 
SELECT employeelist.eid
      ,employeelist.firstName
      ,employeelist.lastName
      ,employeelist.Email_id
      ,employeelist.status
      ,message.mid
      ,message.subject
      ,message.body
      ,message.folder
      ,recipientinfo.rid
      ,recipientinfo.rvalue
      ,referenceinfo.reference
FROM  employeelist
INNER JOIN message       ON employeelist.Email_id = message.sender
INNER JOIN recipientinfo ON message.mid = recipientinfo.mid
INNER JOIN referenceinfo ON recipientinfo.rid = referenceinfo.rfid

我该如何解决?

1 个答案:

答案 0 :(得分:1)

请考虑以下事项:

SELECT * FROM table_a;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
+----+
4 rows in set (0.00 sec)

SELECT * FROM table_b;
+-----+------+
| id  | a_id |
+-----+------+
| 101 |    1 |
| 102 |    1 |
| 103 |    2 |
| 104 |    4 |
| 105 |    4 |
| 106 |    4 |
| 107 |    4 |
+-----+------+
7 rows in set (0.00 sec)

SELECT * FROM table_c;
+------+------+
| id   | a_id |
+------+------+
| 1001 |    2 |
| 1002 |    3 |
| 1003 |    3 |
| 1004 |    4 |
| 1005 |    5 |
| 1006 |    6 |
| 1007 |    7 |
| 1008 |    2 |
| 1009 |    4 |
+------+------+
9 rows in set (0.02 sec)

SELECT *
  FROM table_a a
  JOIN table_b b
    ON b.a_id = a.id
  JOIN table_c c
    ON c.a_id = b.a_id;
+----+-----+------+------+------+
| id | id  | a_id | id   | a_id |
+----+-----+------+------+------+
|  2 | 103 |    2 | 1001 |    2 |
|  4 | 104 |    4 | 1004 |    4 |
|  4 | 105 |    4 | 1004 |    4 |
|  4 | 106 |    4 | 1004 |    4 |
|  4 | 107 |    4 | 1004 |    4 |
|  2 | 103 |    2 | 1008 |    2 |
|  4 | 104 |    4 | 1009 |    4 |
|  4 | 105 |    4 | 1009 |    4 |
|  4 | 106 |    4 | 1009 |    4 |
|  4 | 107 |    4 | 1009 |    4 |
+----+-----+------+------+------+
10 rows in set (0.02 sec)

因此,表a,b和c分别有4行,7行和9行。但是当我们将它们连接在一起时,我们得到10行 - 因此表中的行数与结果中的行数之间没有明显的相关性。