在MySql中结合两个select语句?

时间:2015-01-09 04:07:53

标签: java mysql sql database jsp

我有这张桌子,看看那里。

create table if not exists thread_question
   (
    question_id INT NOT NULL auto_increment,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,
    question_title VARCHAR(500) NOT NULL,
    question VARCHAR(100000) NOT NULL,
    question_dateTime VARCHAR(100) NOT NULL,
    PRIMARY KEY(question_id)
  );

create table if not exists thread_answer
 (
  answer_id INT NOT NULL auto_increment,
  question_id INT NOT NULL references thread_question(question_id),
  first_name VARCHAR(100) NOT NULL,
  last_name VARCHAR(100) NOT NULL,
  answer VARCHAR(100000) NOT NULL,
  answer_dateTime VARCHAR(100) NOT NULL,
  PRIMARY KEY(answer_id)
 );

实际上,我正在建立一个论坛来展示答案,这是完美的。您也可以看到question_id的列已插入thread_question以及thread_answer。我想在一个页面中显示我的答案,有多少用户在那里发布了答案。

所以我可以根据这个问题做到这一点 - > How to show the numbers of answers posted into my forum?

问题

现在我正在尝试将这两个陈述结合起来:

第一声明:

SELECT thread_question.question_id, COALESCE(sub.counts,0) AS NumerOfAnswer 
   FROM thread_question LEFT JOIN (
        SELECT question_id, COUNT(answer_id) AS counts
        FROM thread_answer
        GROUP BY question_id
    ) sub ON thread_question.question_id = sub.question_id ORDER BY NumerOfAnswer asc

第二声明:

select * from thread_question

实际上我想从user's first and second name抓取questionquestion's titlethread_question's table

我确实使用UNION and UNION ALLSELECT( SELECT..)(SELECT..)
但我无法显示结果。它每次都给我一个错误。

请帮助!!
当然,帮助将不胜感激!!

1 个答案:

答案 0 :(得分:1)

由于您在查询中已经有thread_question表,因此只需添加thread_question.*即可添加SELECT thread_question.* -- <<== Use .* to bring all fields , COALESCE(sub.counts,0) AS NumerOfAnswer FROM thread_question LEFT JOIN ( SELECT question_id, COUNT(answer_id) AS counts FROM thread_answer GROUP BY question_id ) sub ON thread_question.question_id = sub.question_id ORDER BY NumerOfAnswer asc ,如下所示:

{{1}}