在 MySql 中合并两个 select 语句?

Combine two select statement in MySql?

我有这张桌子,你看看

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。我想在一个页面上显示我的答案,有多少用户在那里发布了答案。

所以我可以根据这个问题来做 ->

问题

现在我试图将这两个语句结合起来:

第一个语句:

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

实际上我想从 thread_question's table 中获取 user's first and second namequestionquestion's title

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

请帮忙!!
当然,我们将不胜感激!!

因为您已经在查询中包含 thread_question table,所以您需要做的就是添加 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