0

我正在创建两个表。

表 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

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

因此,我通过表单(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.)

.. .Further 我想合并这两个表,以便它给我下面的图像

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

请提出一些建议

谢谢

4

1 回答 1

0

你有一个非常糟糕的数据设计。例如,从 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

于 2013-05-17T14:57:47.593 回答