MySQL,如果第二个表并不总是匹配行,则从两个相关表中获取数据

时间:2012-03-29 11:24:49

标签: mysql sql

示例表格内容

'main'
| id | total |
| 1  | 10    |
| 2  | 20    |
'timed'
| id | id_main | date_from  | date_to    | total |
| 1  | 2       | 2012-03-29 | 2012-04-29 | 50    |

期望的结果

| id | total |
| 1  | 10    |
| 2  | 50    |

不完全正常工作的查询

SELECT main.id AS id, COALESCE(timed.total, main.total) AS total
FROM main
LEFT JOIN timed
ON main.id = timed.id_main
WHERE SYSDATE() BETWEEN timed.date_from AND timed.date_to

结果

| id | total |
| 2  | 50    |

在表'main'和'timed'中,'total'字段永远不会为NULL。 在某些“定时”记录中,没有相对的'id_main',或者会有很少,但它们会有所不同,'date_from''date_to'永远不会相交。 表'main'很大,但'timed'将始终是两个或三个相对记录。

CREATE TABLE `main` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `total` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `main` VALUES (1,10);
INSERT INTO `main` VALUES (2,20);
CREATE TABLE `timed` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_main` int(11) unsigned NOT NULL DEFAULT '0',
  `date_from` date DEFAULT NULL,
  `date_to` date DEFAULT NULL,
  `total` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`),
  KEY `link` (`id_main`)
) ENGINE=InnoDB;
INSERT INTO `timed` VALUES (1,2,'2012-03-29','2012-03-30',50);
ALTER TABLE `timed`
ADD CONSTRAINT `link` FOREIGN KEY (`id_main`) 
REFERENCES `main` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

抱歉我的英文。

1 个答案:

答案 0 :(得分:1)

您应该在连接条件中移动日期条件:

SELECT main.id AS id, COALESCE(timed.total, main.total) AS total
FROM main
LEFT JOIN timed
ON main.id = timed.id_main and SYSDATE() BETWEEN timed.date_from AND timed.date_to

在你的查询中,那些不匹配的行被WHERE条件过滤掉,因为timed.date_form和timed.date_to为null,所以sysdate不能介于它们之间:)