【问题标题】:inserting data into new table from union of two tables从两个表的并集将数据插入新表
【发布时间】:2013-05-13 14:17:01
【问题描述】:

我有一个合并两个表 Table1 和 Table 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

即 电影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   

下面的查询怎么写?

谢谢

【问题讨论】:

    标签: mysql database mysql-workbench


    【解决方案1】:

    使用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;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 2011-09-21
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多