mysql查询无法正常工作

uurity8g  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(315)

我有一个查询问题。我有两个表,一个有点击,另一个有如下转换
表:转换

id | ref id      | registered | tempo     | prod_cod
    ----------------------------
    1  |      1      | 04/05/2018 | 15385950 | oggn-1
    2  |      1      | 05/05/2018 | 15385950 | oggn-1
    3  |      1      | 06/05/2018 | 15385950 | oggn-1

表:单击

id    | ref id      | registered | tempo    | prod_cod | ip        | user_agent 
    ----------------------------
    1  |      1      | 05/05/2018 | 15385950 | oggn-1   | 192.168.1 | Mozilla....
    2  |      1      | 06/05/2018 | 15385950 | oggn-1   | 192.168.1 | Mozilla....
    3  |      1      | 07/05/2018 | 15385950 | oggn-1   | 192.168.1 | Mozilla....

我想通过ref id选择的最近七天的结果是:
表:结果

registered    | clicks      | conversion
    ----------------------------
    04/05/2018 |      0      |  1
    05/05/2018 |      1      |  1
    06/05/2018 |      1      |  1
    07/05/2018 |      1      |  0

这是我的查询,但效果不好,因为如果两个数据库中都不存在注册值,则不会给出所有结果。

SELECT tbl_affiliate_traffic.registered, 
       Count(DISTINCT tbl_affiliate_traffic.id)    AS tarffic, 
       Count(DISTINCT tbl_affiliate_conversion.id) AS conversion 
FROM   tbl_affiliate_traffic CROSS 
       JOIN tbl_affiliate_conversion 
         ON tbl_affiliate_conversion.tempo >= '1524891602' 
            AND tbl_affiliate_conversion.registered = 
                tbl_affiliate_traffic.registered 
            AND tbl_affiliate_conversion.ref_id = '1' 
WHERE  tbl_affiliate_traffic.tempo >= '1524891602' 
       AND tbl_affiliate_traffic.ref_id = '1' 
GROUP  BY registered
sqyvllje

sqyvllje1#

如果可能的话,你不能在一个查询中减慢这个问题的速度,因为在更高的数据量中会花费太多的时间。对这种场景使用两个查询并重新转换数组。
查询1:

SELECT COUNT(*) AS _count,registered FROM `Conversion` GROUP BY registered

在执行这个查询之后,您需要像这样填充数组
$conversion=['04/05/2018'=>1,'05/05/2018'=>1]
问题2:

SELECT COUNT(*) AS _count,registered FROM `Clicks` GROUP BY registered

像这样填充数组“点击”
$clicks=['04/05/2018'=>0,'05/05/2018'=>1]
在那之后,你可以合并这两个数组

foreach($Conversion as $key=>$val){$result[$key]['Conversion'] =  $val}
foreach($Clicks as $key=>$val){$result[$key]['Clicks'] =  $val}

最后,你可以得到结果。

相关问题