查询 #1
SELECT id,letter,IFNULL(date,dt) date FROM mytable,
(SELECT DATE(mindate + INTERVAL (secdiff/2) SECOND) dt
FROM (SELECT mindate,UNIX_TIMESTAMP(maxdate)
- UNIX_TIMESTAMP(mindate) secdiff
FROM (SELECT MIN(date) mindate FROM mytable) N,
(SELECT MAX(date) maxdate FROM mytable) X) AA) A;
样本数据
mysql> DROP TABLE IF EXISTS mytable;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE mytable
-> (
-> id int not null auto_increment,
-> letter char(1),
-> `date` date,
-> primary key (id)
-> );
Query OK, 0 rows affected (0.07 sec)
mysql> INSERT INTO mytable (letter,date) VALUES
-> ('A','2012-01-01'),('B',NULL),('C',NULL),('D','2012-01-15');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM mytable;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | NULL |
| 3 | C | NULL |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.00 sec)
mysql>
查询 #1 已执行
mysql> SELECT id,letter,IFNULL(date,dt) date FROM mytable,
-> (SELECT DATE(mindate + INTERVAL (secdiff/2) SECOND) dt
-> FROM (SELECT mindate,UNIX_TIMESTAMP(maxdate)
-> - UNIX_TIMESTAMP(mindate) secdiff
-> FROM (SELECT MIN(date) mindate FROM mytable) N,
-> (SELECT MAX(date) maxdate FROM mytable) X) AA) A;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | 2012-01-08 |
| 3 | C | 2012-01-08 |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.00 sec)
mysql>
QUERY #2(更简洁的版本)
此查询使用 UNIX 时间戳的平均值。如果所有日期都为 NULL,则使用今天的日期:
SELECT id,letter,IFNULL(date,dt) date FROM mytable,
(
SELECT IF(K=0,DATE(NOW()),avgdt) dt FROM
(SELECT DATE(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(date))))
avgdt FROM mytable) AA,
(SELECT COUNT(date) K FROM mytable) BB
) A;
查询 #2 已执行
mysql> SELECT id,letter,IFNULL(date,dt) date FROM mytable,
-> (
-> SELECT IF(K=0,DATE(NOW()),avgdt) dt FROM
-> (SELECT DATE(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(date))))
-> avgdt FROM mytable) AA,
-> (SELECT COUNT(date) K FROM mytable) BB
-> ) A;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | 2012-01-08 |
| 3 | C | 2012-01-08 |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.05 sec)
mysql>
试试看 !!!