Uselesssss
Uselesssss

Reputation: 2133

Join of two tables as to get entire records

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

Upvotes: 0

Views: 246

Answers (2)

Phil Cross
Phil Cross

Reputation: 9302

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

Upvotes: 2

Sameer Anand
Sameer Anand

Reputation: 274

try this

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

Upvotes: 0

Related Questions