找出是否每天插入mysql表

时间:2015-06-02 06:10:26

标签: mysql sql

我有这张桌子应该每天输入有关车辆里程读数的信息。

CREATE TABLE `table_vehicle_info` (
  `id` int(11) NOT NULL ,
  `reg_no` varchar(50) NOT NULL,
  `vehicle_type` int(11) NOT NULL,
  `engine_no` varchar(50) NOT NULL DEFAULT "DDDD",
  `chassis_no` varchar(50) ,
  `model` int(11) DEFAULT NULL,
  `picture` varchar(50) ,
  `rent` double ,
  `eng_power` int(11) DEFAULT NULL,
  `color` varchar(12) DEFAULT NULL,
  `rent_status` varchar(50) DEFAULT NULL,
  `reg_city` varchar(50) DEFAULT NULL,
  `location` varchar(50) DEFAULT NULL,
  `sub_type` varchar(50)  DEFAULT NULL,
  `purchase_date` date DEFAULT NULL,
  `purchase_amount` double DEFAULT NULL,
  `sum_insured` double DEFAULT NULL,
  `token_tax_amount` double DEFAULT NULL,
  `token_period_from` date DEFAULT NULL,
  `reg_placed_at` varchar(50) DEFAULT NULL,
  `funded_by` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=99 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_readings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `vehicle_id` int(11) NOT NULL,
  `km_driven` int(11) NOT NULL,
  `dt_of_reading` datetime NOT NULL,
  `dt_of_entry` datetime NOT NULL,
  `entry_user` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `vehicle_id` (`vehicle_id`),
  CONSTRAINT `tbl_readings_ibfk_1` FOREIGN KEY (`vehicle_id`) REFERENCES `table_vehicle_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;

INSERT INTO table_vehicle_info (id,reg_no,vehicle_type ) 
VALUES (1, "B-5484",    12  );

INSERT INTO tbl_readings VALUES (NULL,1,100,'2015-6-1',NOW(), 'user');

我想生成一份报告,显示每天都没有输入车辆。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下查询,它会返回tbl_readings中没有第二天条目的所有vehicle_id。

SELECT vehicle_id 
FROM `tbl_readings` 
WHERE DATE(DATE_ADD(dt_of_entry,INTERVAL 1 DAY)) NOT IN 
    (SELECT DATE(dt_of_entry) FROM `tbl_readings`)

修改

试试这个,

SELECT t1.vehicle_id 
FROM `tbl_readings` t1
LEFT JOIN (SELECT vehicle_id, 
        DATE(DATE_ADD(dt_of_reading,INTERVAL -1 DAY)) as reading_date 
    FROM `tbl_readings`) t2 
ON t1.vehicle_id = t2.vehicle_id AND t1.dt_of_reading = t2.reading_date
WHERE t2.vehicle_id IS NULL
GROUP BY t1.vehicle_id
HAVING COUNT(t1.vehicle_id) > 1;

检查fiddle