Join of two tables as to get entire records

こ雲淡風輕ζ 提交于 2019-12-20 05:53:42

问题


I am creating two tables .Table 1 has following schema

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..)

while table 2 has following schema

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)

Now when I put a query to insert values it first checks whether a following username exist in first table .If true then it inserts into second table otherwise it inserts value as per schema into first table.In other words first table has unique usernames and unique user_Id while second contains many repeated usernames with movie they have seen

Now I want to join Table 1 and table 2 ,so that it contains all the colums of both table and a unique user_Id for user_name and the movie they have seen and rating with genre

like for example

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

... and so on

Thanks


回答1:


try this

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



回答2:


SELECT table1.user_id, table2.* 
FROM table2 
INNER JOIN table2
    ON table2.user name = table1.user_name

However, you should structure your database more like this:

table_users:
    user_id
    username
    ...

table_videos:
    video_id
    video_name
    video_genre
    ...

table_rentals
    record_id
    user_id 
    video_id

Then with a structure like that, you would use the following SQL Query:

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 

This is more normalized, and reduces duplicated data



来源:https://stackoverflow.com/questions/16606908/join-of-two-tables-as-to-get-entire-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!