我有以下架构:
我想生成一个包含3列的表格 - 标签的名称,线程的名称,答案数。
示例:
Foo bar 5
Foo something 6
Foo2 somethingElse 3
更重要的是,有一个表“priority_threads”(带有线程的1:1)。我想在这个表中只显示那些优先级线程。
我该怎么做?我完全不知道如何开始。我唯一做的就是:
SELECT tag.name, thread.title, COUNT(answer.id_answer)
FROM tag, thread, answer
WHERE thread.id_tag = tag.id_tag
AND answer.id_thread = thread.id_thread
AND thread.id_thread = priority_threads.id_thread
GROUP BY tag.name, thread.title
ORDER BY tag.name;
然而,使用此查询,答案的count列中的所有值都相同 - 来自Answer表的count(*)...
答案 0 :(得分:1)
试试这个:
SELECT tag.name, thread.title, COUNT(answer.id_answer)
FROM tag
JOIN thread ON
tag.id_tag=thread.id_tag
JOIN answer ON
thread.id_thread = answer.id_thread
JOIN priority_threads
ON thread.id_thread = priority_threads.id_thread
GROUP BY tag.name, thread.title
ORDER BY tag.name;
以下是查询的SQLfiddle链接以进行测试;
示例代码:
CREATE TABLE Tag
(
id_tag int auto_increment primary key,
name varchar(20)
);
INSERT INTO Tag
(name)
VALUES
('Foo'),
('Foo2');
CREATE TABLE Thread
(
id_thread int auto_increment primary key,
id_tag int,
title varchar(20)
);
INSERT INTO Thread
(id_tag, title)
VALUES
(1,'Bar'),
(1,'Something'),
(2,'SomethingElse');
CREATE TABLE Answer
(
id_answer int auto_increment primary key,
id_thread int,
text varchar(200)
);
INSERT INTO Answer
(id_thread, text)
VALUES
(1,'jlkjalkjl'),
(1,'ioioixhakjjkj'),
(1, 'jjalkjijkajk'),
(1, 'jjalkjijkajk'),
(1, 'jjalkjijkajk'),
(2, 'jjalkjijkajk'),
(2, 'jjalkjijkajk'),
(2, 'jjalkjijkajk'),
(2, 'qqweeweraata'),
(2, 'jjalkjijkajk'),
(2, 'jjalkjijkajk'),
(3, 'popoapopop'),
(3, 'zkkasjkljz'),
(3, 'jjalkjijkajk')
;
CREATE TABLE priority_threads
(
id_priority_threads int auto_increment primary key,
id_thread int,
priority int
);
INSERT INTO priority_threads
(id_thread, priority)
VALUES
(1,1),
(3,2);
答案 1 :(得分:0)
这样:
SELECT tag.name, thread.title, COUNT(answer.id_answer)
FROM tag, thread, answer
WHERE thread.id_tag = tag.id_tag
AND answer.id_thread = thread.id_thread
GROUP BY tag.name, thread.title
ORDER BY tag.name;
可能如下所示:
SELECT tag.name, thread.title, COUNT(answer.id_answer)
FROM tag
JOIN thread ON
tag.id_tag=thread.id_tag
JOIN answer ON
thread.id_thread = answer.id_thread
GROUP BY tag.name, thread.title
ORDER BY tag.name;
结果相同,前者是最受欢迎的。好的,但我认为这里的真正问题是你发布的代码中的这一行:
AND thread.id_thread = priority_threads.id_thread
您正在引用另一个表priority_threads,它不在您的查询中。添加联接或删除它,你应该很高兴。
-james