我从三个表中获取数据。 我想在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答案 0 :(得分:1)
在select语句中使用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
答案 1 :(得分: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