2

我正在从三个表中获取数据。我想在jsp页面中显示这些数据。我的问题是加入后数据是多余的

我不想显示冗余数据。

我的桌子是

 create table questions(id integer,title varchar(140),body varchar(2000),
 primary key(id));

 create table question_tags(id integer,tag_name varchar(50),question_id integer,
 primary key(id),foreign key(question_id) references questions(id));


create table answers(id integer,answer varchar(2000),question_id integer,
primary key(id),foreign key(question_id) references questions(id));

查询以获取数据

SELECT questions.*,`question_tags`.*, `answers`.* 
FROM `questions`
JOIN  `answers` 
ON `questions`.`id` = `answers`.`question_id`
JOIN `question_tags` 
ON `questions`.`id` = `question_tags`.`question_id`
WHERE `questions`.`id` = '1'

获取数据后的结果

 ID     TITLE   BODY    TAG_NAME    QUESTION_ID ANSWER
  1     a   hello   java                 1          good
  1     a   hello   java                 1          exellent
  1     a   hello   java                 1          ok
  1     a   hello   mysql                1          good
  1     a   hello   mysql                1          exellent
  1     a   hello   mysql                1          ok
  1         a   hello   jquery               1          good
  1     a   hello   jquery               1          exellent
  1     a   hello   jquery               1          ok

在这里,我正在使用结果集填充数据并在 jsp 中显示

我想在我的jsp中显示以下数据

  question.id|question.title|question.body|tag_names | answers
      1               a           hello       java        good  
                                              mysql       excellent
                                              jquery      ok                               

这仅适用于几行。这里总的o / p行是1 * 3 * 3 = 9如果表中的数据增加了,那么重复的数据就会增加如何解决它。这是上面代码的sql fiddle

4

2 回答 2

1

distinct子句与您的选择语句一起使用以获取没有重复的记录

SELECT distinct questions.*,`question_tags`.*, `answers`.* 
FROM `questions`
JOIN  `answers` 
ON `questions`.`id` = `answers`.`question_id`
JOIN `question_tags` 
ON `questions`.`id` = `question_tags`.`question_id`
WHERE `questions`.`id` = '1'

更新

ResultSet rs = st.execute();   //Assuming that you have the resultset

Set<String> id = new LinkedHashSet<String>();
Set<String> body = new LinkedHashSet<String>();
Set<String> tag_name = new LinkedHashSet<String>();
Set<String> answer = new LinkedHashSet<String>();

while(rs.next())
{
    id.add(rs.getString("id"));
    body.add(rs.getString("body"));
    tag_name.add(rs.getString("tag_name"));
    answer.add(rs.getString("answer"));
}

因为LinkedHashSet唯一不同的值将被存储。现在你需要迭代来填充你的表

注意:这仅限于特定的问题 ID

于 2013-02-21T05:16:07.927 回答
0

我期待的是这个

SELECT  `questions`.`id` AS  `question_id` ,
(
SELECT GROUP_CONCAT(  `question_tags`.`tag_name` SEPARATOR ';') 
FROM  `question_tags` 
WHERE  `question_id` =1
) AS  `Tags` ,
(
SELECT GROUP_CONCAT(  `answers`.`answer` SEPARATOR ';' ) 
FROM  `answers` 
WHERE  `question_id` =1
) AS  `Answers` 
FROM  `questions` 
WHERE  `questions`.`id` =1
于 2013-02-21T13:56:29.440 回答