背景:我是SQL的新手,并且正在使用this homework assignment开设Coursera课程。 Data file here。该数据库包含一个表frequency(docid, term, count)
。
实际问题:为什么以下两个SQLite查询会返回不同的结果? (1)
SELECT count(*)
FROM(
SELECT term
FROM frequency
WHERE docid = '10398_txt_earn' AND count=1
UNION
SELECT term
FROM frequency
WHERE docid = '925_txt_trade' AND count=1);
返回
coun
----
324
(2)
SELECT count(*)
FROM frequency
WHERE (docid = '10398_txt_earn' OR docid = '925_txt_trade') AND count = 1;
返回
coun
----
335
答案 0 :(得分:2)
以下查询给出了325
SELECT count(term)
FROM(
SELECT term
FROM frequency
WHERE docid = '10398_txt_earn' AND count=1
UNION ALL
SELECT term
FROM frequency
WHERE docid = '925_txt_trade' AND count=1
);
问题是UNION合并了重复的结果,因此以下查询
SELECT A.TERM
FROM (
SELECT term
FROM frequency
WHERE docid = '10398_txt_earn' AND count=1
) A
JOIN (
SELECT term
FROM frequency
WHERE docid = '925_txt_trade' AND count=1
) B ON A.term = B.term;
将显示两者中的项目(其中11个)
based
costs
export
july
many
march
month
problems
reuter
speech
world
此查询也会给出相同的结果:
SELECT term
FROM frequency
WHERE docid = '10398_txt_earn' AND count=1
INTERSECT
SELECT term
FROM frequency
WHERE docid = '925_txt_trade' AND count=1;