我有下面的架构
CREATE TABLE `vocabulary` (
`vid` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255),
PRIMARY KEY vid (`vid`)
);
CREATE TABLE `term` (
`tid` int(10) unsigned NOT NULL auto_increment,
`vid` int(10) unsigned NOT NULL default '0',
`name` varchar(255),
PRIMARY KEY tid (`tid`)
);
CREATE TABLE `article` (
`aid` int(10) unsigned NOT NULL auto_increment,
`body` text,
PRIMARY KEY aid (`aid`)
);
CREATE TABLE `article_index` (
`aid` int(10) unsigned NOT NULL default '0',
`tid` int(10) unsigned NOT NULL default '0'
)
INSERT INTO `vocabulary` values (1, 'vocabulary 1');
INSERT INTO `vocabulary` values (2, 'vocabulary 2');
INSERT INTO `term` values (1, 1, 'term v1 t1');
INSERT INTO `term` values (2, 1, 'term v1 t2 ');
INSERT INTO `term` values (3, 2, 'term v2 t3');
INSERT INTO `term` values (4, 2, 'term v2 t4');
INSERT INTO `term` values (5, 2, 'term v2 t5');
INSERT INTO `article` values (1, "");
INSERT INTO `article` values (2, "");
INSERT INTO `article` values (3, "");
INSERT INTO `article` values (4, "");
INSERT INTO `article` values (5, "");
INSERT INTO `article_index` values (1, 1);
INSERT INTO `article_index` values (1, 3);
INSERT INTO `article_index` values (2, 2);
INSERT INTO `article_index` values (3, 1);
INSERT INTO `article_index` values (3, 3);
INSERT INTO `article_index` values (4, 3);
INSERT INTO `article_index` values (5, 1);
INSERT INTO `article_index` values (5, 4);
实施例。选择一个defiend词汇表的术语(具有非零文章索引),例如VID = 2
select a.tid, count(*) as article_count from term t JOIN article_index a
ON t.tid = a.tid where t.vid = 2 group by t.tid;
+-----+---------------+ | tid | article_count | +-----+---------------+ | 3 | 3 | | 4 | 1 | +-----+---------------+
问题:
SQL:不正确,因为article_count错误
SELECT t.tid, count(*) as c FROM term t JOIN article_index i ON t.tid = i.tid WHERE t.vid = 1 AND i.aid IN
( SELECT i.aid FROM term t JOIN article_index i ON t.tid = i.tid WHERE i.tid = 3)
GROUP BY t.tid ;
结果:
+-----+---------------+ | tid | article_count | +-----+---------------+ | 1 | 2 | +-----+---------------+
预期结果:由于只有一篇文章与tid = 3和tid = 1
相关联+-----+---------------+ | tid | article_count | +-----+---------------+ | 1 | 1 | +-----+---------------+
答案 0 :(得分:1)
它不是很好但很容易到达
SELECT tid, count(*)
FROM
(
SELECT distinct t.tid
FROM term t
JOIN article_index i
ON t.tid = i.tid
WHERE t.vid = 1
AND i.aid IN
( SELECT i.aid
FROM term t
JOIN article_index i
ON t.tid = i.tid
WHERE i.tid = 3)
) t
GROUP BY tid
答案 1 :(得分:0)
您只需将count(*)
替换为count(distinct t.vid)
...