我有这张 table ,看看那里。
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
实际上,我想从thread_question 的表
中获取用户的名字和名字
、问题
和问题的标题
。
我确实使用了 UNION 和 UNION ALL
和 SELECT( SELECT..)(SELECT..)
。
但我无法显示结果.每次都给我一个错误。
请帮忙!!
当然,我们将不胜感激!!
最佳答案
由于您在查询中已经有了 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
关于java - 在 MySql 中合并两个 select 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27853673/