gpt4 book ai didi

mysql - 使用什么才能在 Mysql 中拥有完整的合并表

转载 作者:行者123 更新时间:2023-11-30 01:37:52 25 4
gpt4 key购买 nike

我正在创建两个表。

表 1 具有以下架构

user_id       int            not null,autoincrement
movie _id int not null
movie_name varchar
user_name varchar
rating int
genre varchar

表 2 具有以下架构

movie _id     int            not null 
movie_name varchar
user_name varchar
genre varchar
rating varchar

现在,当我进行查询插入值时,它首先检查第一个表中是否存在以下用户名。如果为 true,则它插入到第二个表中,否则它将根据架构将值插入到第一个表中。换句话说,第一个表具有唯一的用户名和唯一的 user_Id,而第二个包含许多重复的用户名以及他们看过的电影

因此,我通过表单(Java,servlet)将以下值插入到我的表中

user_Id    movie_Id    movie_name      user_name   rating  genre
1 1 Twister Alex 6 Drama
2 1 Twister Tim 1 Drama
3 2 sweet november pam 5 Romantic
4 3 The pianist carl 5 Drama
5 4 narnia stephen 7 Fantasy
..
..
(contd..)

表2

    movie_Id   movie_Name    user_name     genre     Rating
2 sweet november Alex Romantic 4
3 The pianist Alex Drama 5
4 narnia Pam Fantasy 8
9 maceth Tim Drama 9
..
....

(contd.)

...此外,我想合并两个表,以便它给我以下图像

user_id   movie_Id  movie_name      user_name   rating  genre
1 1 Twister Alex 6 Drama
1 2 sweet november Alex 4 Romantic
1 3 The pianist Alex 5 Drama
2 1 Twister Tim 1 Drama
2 9 macbeth Tim 9 Drama
3 2 Sweet November Pam 5 Romatic
3 4 Narnia Pam 8 Fantasy
4 3 The Pianist Carl 5 Drama
5 4 Narnia Stephen 7 Fantasy
... and so on

What should I use

我尝试使用连接,但它忽略了第一个表值。我想在我在表单中输入值然后单击后立即获得两个表值

这是我使用的以下语法

select * from table2 inner join table1 on table2.user_name = table1.user_name

请提出建议

谢谢

最佳答案

你的数据设计非常糟糕。例如,从 table2 到 table1 没有明显的链接。它应该有一个 user_id 列,而不是 user_name

但是,您问题的答案是union all,而不是join(或者更确切地说,除了)。您需要一个联接来查找第二个表的 user_id:

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;

也就是说,您应该修改数据库结构。作为提示,它应该具有三个表:usersmoviesuser_movies

关于mysql - 使用什么才能在 Mysql 中拥有完整的合并表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com