改进SQL查询,以便我只能在已经插入的日期之后获得日期

时间:2012-01-05 08:48:56

标签: mysql

我正在尝试改进我的SQL查询,以便我只能从f_facts表中获取最新信息,并且我正在检查date_id是否是新信息

由于某种原因,这个查询对我不起作用:

REPLACE INTO `r_views`
        SELECT network_id, type_id, topic_id, COUNT(*), date_id, 
        SUM( IF (`d_refer`.`refer` LIKE '%facebook%', 1,0) ) AS `facebook`, 
        SUM( IF (`d_refer`.`refer` LIKE '%twitter%', 1,0) ) AS `twitter`, 
        SUM( IF ( (`d_refer`.`refer` LIKE '%hotmail%' or `d_refer`.`refer` LIKE '%live%' or `d_refer`.`refer` LIKE '%gmail%' or `d_refer`.`refer` LIKE '%mail.%'), 1,0) ) AS `email`, 
        SUM( IF (`d_refer`.`refer` LIKE '%google%', 1,0) ) AS `google`      

        FROM `f_facts` 
        LEFT JOIN `d_date` ON `f_facts`.`date_id` = `d_date`.`id` 
        LEFT JOIN `d_refer` ON `f_facts`.`refer_id` = `d_refer`.`id` 

        WHERE `action_id`=3 AND `type_id` != 17 AND `date_id` > (SELECT `date_id` FROM `r_views` ORDER BY `date_id` DESC LIMIT 1) GROUP BY topic_id, date_id

这是我的旧sql查询,它正在读取来自f_facts表的所有数据,这是无效的:

REPLACE INTO `r_views`
        SELECT network_id, type_id, topic_id, COUNT(*), date_id, 
        SUM( IF (`d_refer`.`refer` LIKE '%facebook%', 1,0) ) AS `facebook`, 
        SUM( IF (`d_refer`.`refer` LIKE '%twitter%', 1,0) ) AS `twitter`, 
        SUM( IF ( (`d_refer`.`refer` LIKE '%hotmail%' or `d_refer`.`refer` LIKE '%live%' or `d_refer`.`refer` LIKE '%gmail%' or `d_refer`.`refer` LIKE '%mail.%'), 1,0) ) AS `email`, 
        SUM( IF (`d_refer`.`refer` LIKE '%google%', 1,0) ) AS `google`      

        FROM `f_facts` 
        LEFT JOIN `d_date` ON `f_facts`.`date_id` = `d_date`.`id` 
        LEFT JOIN `d_refer` ON `f_facts`.`refer_id` = `d_refer`.`id` 

        WHERE `action_id`=3 AND `type_id` != 17 GROUP BY topic_id, date_id 

1 个答案:

答案 0 :(得分:1)

我认为你可以在三点加强查询:

1)您可以使用此电子邮件列代替OR:

SUM( IF ( (`d_refer`.`refer` LIKE '%live%' or `d_refer`.`refer` LIKE '%mail.%'), 1,0) ) AS `email`

2)你真的需要这两个联盟吗?他们在我看来有点多余。

3)在日期添加索引