可以为null的字段之间的连接视图

时间:2016-02-14 15:09:34

标签: mysql join view

我有2个表,每个表有超过50,000个记录,每个表都有。

CREATE TABLE IF NOT EXISTS `call_attempt` (
  `csvleads_id_fk` int(11) NOT NULL,
  `users_id_fk` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  `call_id` varchar(50) default NULL,
  KEY `csvlead` (`csvleads_id_fk`),
  KEY `user_id` (`users_id_fk`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `recorded` (
  `record_id` int(11) NOT NULL auto_increment,
  `agent_id_fk` int(11) NOT NULL,
  `lead_id_fk` int(11) NOT NULL,
  `duration` int(11) NOT NULL,
  `recording_url` text collate utf8_unicode_ci NOT NULL,
  `recorded_at` timestamp NULL default NULL,
  `call_id` varchar(50) character set utf8 default NULL,
  PRIMARY KEY  (`record_id`),
  UNIQUE KEY `filterme` (`recording_url`(100))
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=72158 ;

我添加了一个call_id字段来建立链接。这意味着新记录必须填写这些字段,至少在表 call_attempt 中。

  call_attempt               recorded
-------------------       ----------------
users_id_fk call_id       call_id dutarion
-------------------       ----------------
1            NULL         NULL    10
2            NULL         NULL     8
3            NULL         NULL     5
4            NULL         ca12    19
50000        ca12         ca14     9
50001        ca13
50002        ca14         

我需要向我展示表格中所有记录 call_attempt ,如果您在表格记录中找到记录,则会带来持续时间。

我尝试了LEFT JOIN但需要超过50秒。

SELECT 
        `cal`.`csvleads_id_fk` AS `Id`,
        `rc`.`duration` AS `duration`
    FROM `call_attempt` AS cal       
        LEFT JOIN recorded AS rc ON (cal.call_id = rc.call_id AND (rc.call_id IS NOT NULL))

84.625秒/0.000秒

接下来,我尝试对SELECT表录制进行LEFT JOIN,只有 call_id 的记录不是NULL但不允许我创建视图。

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `benscott`@`%` 
    SQL SECURITY DEFINER
VIEW `callHistory4` AS
SELECT 
        `cal`.`csvleads_id_fk` AS `Id`,        
        `rc`.`duration` AS `duration`
    FROM `call_attempt` AS cal              
        LEFT JOIN (SELECT call_id , duration FROM `recorded` WHERE call_id IS NOT NULL) AS rc ON (rc.call_id = cal.call_id)

错误代码:1349。查看的SELECT包含FROM子句中的子查询

然后我使用 call_id 中的结果NOT NULL创建另一个视图。

CREATE 
    ALGORITHM = UNDEFINED 
    DEFINER = `benscott`@`%` 
    SQL SECURITY DEFINER
VIEW `view_recorded` AS
SELECT call_id , duration FROM `recorded` WHERE call_id IS NOT NULL

在新视图中,我加入了view_recorded,但也需要超过40秒。

SELECT 
        `cal`.`csvleads_id_fk` AS `Id`,
        `rc`.`duration` AS `duration`
    FROM `call_attempt` AS cal       
        LEFT JOIN view_recorded AS rc ON (rc.call_id = cal.call_id)

92.094秒/0.000秒

那么,我有什么选择?谢谢!!

1 个答案:

答案 0 :(得分:0)

对于此查询:

SELECT `cal`.`csvleads_id_fk` AS `Id`, `rc`.`duration` AS `duration`
FROM `call_attempt_log` cal LEFT JOIN
     recorded_calls rc
     ON cal.call_id = rc.call_id AND rc.call_id IS NOT NULL;

最佳指数为recorded_calls(call_id, duration)