如何在同一列SQL上多次使用SELECT查询

时间:2013-05-30 15:19:07

标签: mysql sql select

我正在尝试根据交叉表信息生成两列。具体来说,我正在尝试选择在讨论论坛中提问的学生,并将他们放入“提问者”专栏,并选择回答问题的学生,并将其放入“回答者”专栏。查询单独工作,但是当我用逗号连接它们时,我得到这个语法错误:

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语法。

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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'

答案 2 :(得分: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