我有两张桌子:
Table 1
+--------+-----+-----+
| name | id1 | id2 |
+--------+-----+-----+
| luis | 1 | 1.2 |
+--------+-----+-----+
| carlos | 2 | 1.3 |
+--------+-----+-----+
| george | 3 | 1.5 |
+--------+-----+-----+
Table 2
+--------+-----+-----+
| points | id1 | id2 |
+--------+-----+-----+
| 100 | 1 | 1.2 |
+--------+-----+-----+
| 50 | 6 | 2 |
+--------+-----+-----+
| 48 | 3 | 1.5 |
+--------+-----+-----+
我希望在两个表中id1和id2相等时搜索所有情况,并将第二个表的记录保存为新表。
对于这种情况,它将是:
Table 3
+--------+-----+-----+
| points | id1 | id2 |
+--------+-----+-----+
| 100 | 1 | 1.2 |
+--------+-----+-----+
| 48 | 3 | 1.5 |
+--------+-----+-----+
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以使用CREATE TABLE ... AS SELECT ...
语法和JOIN
table1
以及table2
与id1
和id2
:
CREATE TABLE Table3 AS
SELECT Table2.*
FROM Table2
JOIN Table1
ON Table2.id1 = Table1.id1
AND Table2.id2 = Table2.id2;
答案 2 :(得分:1)
CREATE TABLE table3 AS
SELECT table1.points, table1.id1, table2.id2
FROM table1 INNER JOIN table2 ON table1.id1 = table2.id1 AND table1.id2 = table2.id2;
答案 3 :(得分:1)
使用exists有点多,但它有效。对于你所要求的,只需INNER JOIN这两个表就会简单得多。
INSERT INTO `table3` (points, id1, id2)
SELECT bar.points, bar.id1, bar.id2
FROM bar
INNER JOIN foo ON bar.id1 = foo.id1
AND bar.id2 = foo.id2
;
答案 4 :(得分:0)
使用SQL INSERT INTO SELECT
语句和LEFT JOIN
:从table2
获取相应的详细信息,其中id1
和id2
对应table1
中的值{1}},并将它们插入第三个表格(table3
):
INSERT INTO table3 AS t3 (points, id1, id2)
SELECT
t2.points,
t2.id1,
t2.id2
FROM table2 AS t2
LEFT JOIN table1 AS t1 ON (t1.id1 = t2.id1 AND t1.id2 = t2.id2);