我创建了三个表
在这里,我想获取与特定问题(id)相关的所有question_tags和答案。 为此需要单个查询或存储过程
create table questions(id varchar(100),title varchar(140),body varchar(2000),
primary key(id));
create table question_tags(id varchar(50),tag_name varchar(50),question_id varchar(100),
primary key(id),foreign key(question_id) references questions(id));
create table answers(id varchar(50),answer varchar(2000),question_id varchar(100),
primary key(id),foreign key(question_id) references questions(id));
以及表格中的以下数据
mysql> select * from questions;
+----+-------+-------------+
| id | title | body |
+----+-------+-------------+
| 1 | a | hello |
| 2 | b | hii |
| 3 | c | bye |
| 4 | d | how are you |
+----+-------+-------------+
4 rows in set (0.03 sec)
mysql> select * from question_tags
+----+----------+-------------+
| id | tag_name | question_id |
+----+----------+-------------+
| t1 | java | 1 |
| t2 | mysql | 1 |
| t3 | jquery | 1 |
+----+----------+-------------+
3 rows in set (0.00 sec)
mysql> select * from answers;
+----+-----------+-------------+
| id | answer | question_id |
+----+-----------+-------------+
| a1 | good | 1 |
| a2 | excellent | 1 |
| a3 | ok | 1 |
+----+-----------+-------------+
3 rows in set (0.00 sec)
答案 0 :(得分:1)
我认为您搜索JOIN [ON]语句。对于你的Tablelayout,它应该是这样的:
SELECT `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` = {YOUR_ID}
或仅问题ID,答案,标签:
SELECT `questions`.`id` AS `question_id`,
`question_tags`.`tag_name`,
`answers`.`answer`
FROM `questions`
JOIN `answers`
ON `questions`.`id` = `answers`.`question_id`
JOIN `question_tags`
ON `questions`.`id` = `question_tags`.`question_id`
WHERE `questions`.`id` = 0
修改强> 对于一行中的所有事情:
SELECT `questions`.`id` AS `question_id` ,
(
SELECT GROUP_CONCAT( `question_tags`.`tag_name` SEPARATOR ';')
FROM `question_tags`
WHERE `question_id` =0
) AS `Tags` ,
(
SELECT GROUP_CONCAT( `answers`.`answer` SEPARATOR ';' )
FROM `answers`
WHERE `question_id` =0
) AS `Answers`
FROM `questions`
WHERE `questions`.`id` =0
请注意,不是这样做的最佳方法。因为我不熟悉MySQL中的SP,所以我无法为您提供存储过程。 在我的意见中,没有办法选择/返回/显示您想要的格式作为表格。
答案 1 :(得分:-1)
查询是:
select * from questions join question_tags on (questions.id = question_tags.question_id) join answers on (questions.id=answers.question_id);
Here是一个小提琴;如果你提供一个问题,它可以帮助我们
请阅读有关mySQL命名约定(有关表格的表格)和关键引用(我已将您的更改为integer
,但您也可以auto_increment
等)。