加入两个表以获得完整记录
我正在创建两个表。表1具有以下模式
user_id int not null,autoincrement movie _id int not null movie_name varchar user_name varchar rating int genre varchar user_Id movie_Id movie_name user_name rating genre 1 1 Twister Alex 6 Drama 2 ! Twister Tim 1 Drama (contd..)
而表2有以下架构
movie _id int not null movie_name varchar user_name varchar genre varchar movie_Id movie_Name user_name genre 2 Harry Porter Alex Fantay 3 Narnia Alex Fantasy .. ...(contd)
现在,当我查询插入值时,它首先检查第一个表中是否存在以下用户名。如果为true,则将其插入到第二个表中,否则它会根据模式将值插入到第一个表中。换句话说,第一个表具有唯一的用户名和唯一user_Id,而second包含许多重复的用户名,他们看过电影
现在我想加入表1和表2,以便它包含表的所有列和user_name的唯一user_Id以及他们看过的电影和类型的评级
比如说
user_id movie_Id movie_name user_name rating genre 1 1 Twister Alex 6 Drama 1 2 Harry Porter Alex 7 Fantasy 1 3 Narnia Alex 6 Fantasy 2 1 Twister Tim 1 Drama
… 等等
谢谢
试试这个
select * from table2 inner join table1 on table2.user_id= table1.user_id
SELECT table1.user_id, table2.* FROM table2 INNER JOIN table2 ON table2.user name = table1.user_name
但是,您应该更像这样构建数据库:
table_users: user_id username ... table_videos: video_id video_name video_genre ... table_rentals record_id user_id video_id
然后使用这样的结构,您将使用以下SQL查询:
SELECT table_users.user_id, table_users.username, table_videos.video_id, table_videos.video_name FROM table_videos INNER JOIN table_rentals ON table_rentals.video_id = table_videos.video_id INNER JOIN table_users ON table_rentals.user_id = table_users.user_id
这更加规范化,并减少重复数据