从两个表的并集将数据插入新表

时间:2013-05-18 14:46:33

标签: mysql database mysql-workbench

我有一个以下查询,联合两个表Table1和表2

ResultSet res = st.executeQuery(" select user_id, movie_Id, movie_name, user_name, rating, genre from Table1 union all select t1.user_id, t2.movie_Id, t2.movie_name, t2.user_name,  t2.rating, t2.genre from Table2 t2 join Table1 t1 on t2.user_name = t1.user_name;");

输出 -

1   12  pianist                 vishal  7   action
2   4   titanic                 rajesh  7       action
3   5   snakes on a plane   anuj    2   drama
4   9   oh my god           arun    5   drama
5   9   jumanji                 vishal  8   fantasy
6   68  the rabbit hole         vishal  4   mystery
1   249 fast and furious    vishal  0   action
2   356 sun and horse           rajesh  0   fantasy
2   423 scream                  rajesh  0   comedy
2   391 alone                   rajesh  0   tragedy
2   739 price and pauper    rajesh  0   drama
4   451 seven                   arun    5   comedy
5   9   ghosts                  vishal  0   horror
5   216 face off            vishal  0   comedy
5   344 future                  vishal  0   drama
5   387 night and day           vishal  0   suspense
5   249 fast and furious    vishal  0   action
6   9   ghosts                  vishal  0   horror
6   216 face off            vishal  0   comedy
6   344 future                  vishal  0   drama
6   387 night and day           vishal  0   suspense
6   249 fast and furious    vishal  0   action

现在我希望我应该将从此处传来的值插入表3,但只能插入movie_Id,user_Id和rating

即 movie_id int user_Id int 评级varchar

user_Id movie_Id    rating
1   12      7   
2   4       7   
3   5       2   
4   9       5   
5   9       8   
6   68      4   
1   249     0   
2   356     0   
2   423     0   
2   391     0   
2   739     0   
4   451     5   
5   9       0   
5   216     0   
5   344     0   
5   387     0   
5   249     0   
6   9       0   
6   216     0   
6   344     0   
6   387     0   
6   249     0   

如何为以下内容编写查询?

由于

1 个答案:

答案 0 :(得分:0)

使用INSERT INTO ... SELECT ...

INSERT INTO table3(movie_id, user_id, rating)
SELECT movie_id, user_id, rating
FROM
(
    SELECT movie_Id, user_id, rating
    FROM Table1 
    UNION ALL
    SELECT t2.movie_id, t1.user_id, t2.rating
    FROM Table2 t2 
    JOIN Table1 t1 ON t2.user_name = t1.user_name
) AS t;