-2
SELECT 
  (COUNT(v1.id) * 2) + (COUNT(v2.id) * 0.5) AS total,
  COUNT(v1.id) AS votes,
  COUNT(v2.id) AS visits
FROM
   votes AS v1,
   visits AS v2
;

实际上,此查询的投票和访问结果为 1710,但投票有 18 行,访问次数为 98 ......有人知道为什么吗?并且有什么解决办法吗?

正确的返回值是:
总计 85
18 票
98 次访问

当前结构:
http ://sqlfiddle.com/#!2/b7604/1

4

3 回答 3

3

您在这里所做的称为交叉连接或交叉产品 - 对于来自投票的每一行,您从访问中获取所有行。

于 2013-08-09T03:51:27.260 回答
2

尝试,

SELECT SUM(VisitsCount) + SUM(VotesCount) AS TOTAL,  SUM(VisitsCount) AS VISITS, SUM(VotesCount) AS VOTES
FROM (

  SELECT COUNT(id) AS VotesCount, 0 AS VisitsCount, 1 AS Gr
  FROM votes

  UNION 

  SELECT 0 AS VotesCount, COUNT(ID) AS VisitsCount, 1 AS Gr
  FROM visits

  ) t 

GROUP BY Gr

检查SQL 小提琴

于 2013-08-09T04:41:28.257 回答
0

您应该查看 UNION 操作而不是您正在执行的 CROSS JOIN

它看起来像:

SELECT 
  whatever
FROM
   (SELECT whatever1 FROM votes) AS v1 UNION (SELECT whatever2 FROM visits) AS v2

我不知道 mySQL 中的语法是怎样的,而且我确实质疑用一条“选择”指令列出这 3 个值的可能性。就算可行,也绝对不值得头疼!!!

于 2013-08-09T04:34:11.797 回答