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次访问
答案 0 :(得分:3)
你在这里所做的事情称为交叉加入或交叉产品 - 对于每一行的投票,你从访问中获取所有行。
答案 1 :(得分: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
答案 2 :(得分:0)
你应该看看UNION操作而不是你正在做的CROSS JOIN
看起来像是:
SELECT
whatever
FROM
(SELECT whatever1 FROM votes) AS v1 UNION (SELECT whatever2 FROM visits) AS v2
我不知道mySQL中的语法是怎样的,我确实怀疑用一条“select”指令列出这3个值的可能性。即使它是可行的,它绝对不值得头疼!