0

我创建了三个表

在这里,我想获取与特定问题(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)
4

2 回答 2

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。在我看来,没有办法选择/返回/显示您想要的格式作为表格。

于 2013-02-20T11:18:20.617 回答
-1

查询是:

select * from questions join question_tags on (questions.id = question_tags.question_id) join answers on (questions.id=answers.question_id);

是一个小提琴;如果您向我们提供您的问题,它会极大地帮助我们帮助您。
请阅读有关 mySQL 命名约定(符号表)和 keyreferences 的信息(我已将您的更改为integers,但您也可以auto_increment等)。

于 2013-02-20T11:19:13.057 回答