简体   繁体   English

MySQL查询中的多个联接给出错误的结果

[英]Multiple joins in a MySQL query giving incorrect results

I've got a large mysql query with 5 joins which may not seem efficient but I'm struggling to find a different solution which would work. 我有一个带有5个联接的大型mysql查询,这看似效率不高,但我正在努力寻找可行的其他解决方案。

The views table is the main table here, because both clicks and conversions table rely on it via the token column(which is indexed and set as a foreign key in all tables). views表是这里的主表,因为clicks和conversions表都通过token列(在所有表中都被索引并设置为外键)依赖于它。

The query: 查询:

SELECT 
var.id,
var.disabled,
var.name,
var.updated,
var.cid,
var.outdated,
IF(var.type <> 0,'DL','LP') AS `type`,
COUNT(DISTINCT v.id) AS `views`, 
COUNT(DISTINCT c.id) AS `clicks`,
COUNT(DISTINCT co.id) AS `conversions`,
SUM(tc.cost) AS `cost`,
SUM(cp.value) AS `revenue`

FROM variants AS var

LEFT JOIN views AS v ON v.vid = var.id
LEFT JOIN traffic_cost AS tc ON tc.id = v.source
LEFT JOIN clicks AS c ON c.token = v.token
LEFT JOIN conversions AS co ON co.token = v.token
LEFT JOIN c_profiles AS cp ON cp.id = co.profile

WHERE var.cid = 28
GROUP BY var.id

The results I'm getting are: 我得到的结果是: 在此处输入图片说明

The problem is the revenue and cost results are too hight, because for views,clicks and impressions only the distinct rows are counted, but for revenue and cost for some reason(I would really appreciate an explanation here) all rows in all tables are taken into the result set. 问题是收入和成本结果太高,因为对于视图,点击和印象,仅计算不同的行,但是出于某种原因(对于我在这里的解释非常感谢),对于收入和成本,所有表中的所有行均被采用放入结果集中

I know this is a large query, but both clicks and conversions tables rely on the views table which is used for filtering the results eg views.country = 'uk'. 我知道这是一个很大的查询,但是点击表和转化表都依赖于用于过滤结果的视图表,例如views.country ='uk'。 I've tried doing 3 queries and merging them, but that didn't work(it gave me wrong results). 我尝试做3个查询并将其合并,但这没有用(它给了我错误的结果)。

One more thing that I find weird is that if I remove the joins with clicks, conversions, c_profiles the costs column shows correct results. 我觉得很奇怪的另一件事是,如果我删除包含点击,转化和c_profiles的联接,则“费用”列将显示正确的结果。

Any help would be appreciated. 任何帮助,将不胜感激。

In the end I had to use 3 different queries and do a merge on them. 最后,我不得不使用3个不同的查询并对其进行合并。 Seemed like an overhead, but worked for me. 看起来像头顶上的东西,但为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM