1

我正在尝试根据交叉表信息生成两列。具体来说,我试图选择在论坛中提出问题的学生,并将其放入“提问者”列,并选择回答问题的学生,并将其放入“回答者”列。查询单独工作,但是当我按如下方式通过逗号加入它们时,会出现以下语法错误:

SELECT author_id AS questioner
WHERE post_type='question',
group_concat(DISTINCT author_id SEPARATOR " ") AS answerers
WHERE post_type='answer'
FROM students;

语法错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
group_concat(DISTINCT author_id SEPARATOR " ") AS answerers
FROM students
WHERE' at line 12

我如何获得一列提出问题的人和一列回答问题的人?我假设错误来自对 SELECT 语法的误解。

4

3 回答 3

3

我知道这适用于 SQL 服务器,但您可以在 MySQL 中尝试

SELECT a.author_id AS questioner, b.author_id AS answerers
FROM students a, students b
WHERE a.post_type='question'
AND b.post_type='answer'
于 2013-05-30T15:28:49.197 回答
2

试试这个,我认为这是你想要的:

SELECT
  s1.author_id AS questioner,
  (SELECT group_concat(DISTINCT author_id SEPARATOR " ") FROM students s2 WHERE s2.post_type = 'answer' AND s2.thread_id = s1.thread_id) AS answerers
FROM
  students s1
WHERE
  s1.post_type = 'question'
于 2013-05-30T16:28:15.310 回答
1

我不明白你为什么要首先发出两个 FROM (无论如何都是不允许的)。如果您想在单个查询中获得两个选择,您可以这样做(查询未测试):

SELECT author_id, post_type AS questioner
FROM students
WHERE post_type='question' OR post_type='answer';

如果需要在一条语句中进行两次查询,则需要使用子查询:http ://dev.mysql.com/doc/refman/5.0/en/subqueries.html

于 2013-05-30T15:24:43.590 回答