2013-02-21 40 views
2

我正在從三個表中提取數據。 我想在jsp頁面中顯示這些數據。 我的問題是,加入後數據是多餘的如何在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)); 

查詢使用結果集獲取數據

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 

在這裏,我fatching數據和JSP

顯示後

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' 

結果來提取數據

我想在我的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上面的代碼

回答

1

使用distinct子句SELECT語句來獲得無重複記錄

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

+0

不工作顯示所有9行 – 2013-02-21 06:28:28

+0

怎麼辦你希望顯示你的結果? – asifsid88 2013-02-21 06:28:57

+0

question.id,question.title,question.body, tag_names(java,mysql,jquery) answers(good,excellent,ok)請參閱http://sqlfiddle.com/#!2/e9606/21 – 2013-02-21 06:30:58

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