要使用原始查询执行此操作,请将 count 调用更改为COUNT(idWord1). 这将导致它计算 idWord1 为 NOT NULL 的次数。现在它正在计算行数,所以你得到一个 1,你应该得到一个零。
这是我的示例数据集:
words2
-------
idWord
-------
foo
bar
baz
biz
buzz
links2
-------
idWord1 | idWord2
-------
foo | bar
foo | baz
bar | baz
buzz | foo
buzz | bar
(此数据集忽略idUserandlinkType字段,因为您的原始问题没有描述它们的使用方式,并且它们似乎与答案无关。)
当我在我的数据集上运行您的查询时,我得到了这个:
idWord | idWord1 | idWord2 | linkCount
--------------------------------------
bar | bar | baz | 3
baz | NULL | NULL | 2
biz | NULL | NULL | 1
buzz | buzz | foo | 2
foo | foo | bar | 3
另请注意,COUNT(*)根据您使用的存储引擎,这将更加昂贵。有关详细信息,请参阅其他问题。
当我将计数更改为COUNT(idWord1)我得到这个:
idWord | idWord1 | idWord2 | linkCount
--------------------------------------
bar | bar | baz | 3
baz | NULL | NULL | 2
biz | NULL | NULL | 0
buzz | buzz | foo | 2
foo | foo | bar | 3
这是一个更简单的查询,它不使用子查询并使用语句将 words2 连接到 links2 OR:
SELECT
words2.idWord
-- this will count the number of links to each word
-- if there are no links the COUNT() call will return 0
, COUNT(idWord1) AS linkCount
FROM words2
LEFT JOIN links2
ON words2.idWord = links2.idWord1
OR words2.idWord = links2.idWord2
GROUP BY words2.idWord
ORDER by words2.idWord
在示例数据集上运行时,我得到以下结果:
idWord | linkCount
-------------------
bar | 3
baz | 2
biz | 0
buzz | 2
foo | 3