SQL Server:如何使用不同的innerjoin

时间:2017-07-23 04:19:16

标签: sql sql-server

我需要选民数量;

SELECT voter, COUNT(voter) as numvoters
FROM TxVotes
WHERE timestamp >= '2017-07-22' AND
      timestamp < '2017-07-23'
GROUP BY voter
ORDER BY COUNT(voter) DESC

使用DISTINCT进行内连接(添加DISTINCT作者)

SELECT v.voter, COUNT(v.voter) as numvoters
FROM TxVotes v JOIN
     Comments c
     ON v.voter = DISTINCT c.author 
WHERE v.timestamp >= '2017-07-21' AND
      v.timestamp < '2017-07-22' AND
      c.body LIKE '"ko"'
GROUP BY v.voter
ORDER BY COUNT(v.voter);

但它不起作用......

如何使用不同的内连接?

1 个答案:

答案 0 :(得分:2)

应该这样做

SELECT v.voter, COUNT(v.voter) as numvoters
FROM TxVotes v JOIN
     (select DISTINCT c.author from  Comments c where c.body LIKE '"ko"') c
     ON v.voter = c.author
WHERE v.timestamp >= '2017-07-21' AND
      v.timestamp < '2017-07-22' 
GROUP BY v.voter
ORDER BY COUNT(v.voter);

但我更喜欢使用Exists

执行此操作
SELECT v.voter, COUNT(v.voter) as numvoters
FROM TxVotes v 
WHERE v.timestamp >= '2017-07-21' AND
      v.timestamp < '2017-07-22' AND 
      Exists (select 1 from Comments c where c.body LIKE '"ko"' and v.voter = c.author)
GROUP BY v.voter
ORDER BY numvoters;