mysql选择包含最高值的记录,在包含空值的列的范围内连接

mysql选择包含最高值的记录,在包含空值的列的范围内连接,mysql,join,distinct,Mysql,Join,Distinct,以下是我的工作内容: CREATE TABLE IF NOT EXISTS `rate` ( `id` int(11) NOT NULL AUTO_INCREMENT, `client_company` int(11) DEFAULT NULL, `client_group` int(11) DEFAULT NULL, `client_contact` int(11) DEFAULT NULL, `role` int(11) DEFAULT NULL, `date_fro

以下是我的工作内容:

CREATE TABLE IF NOT EXISTS `rate` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `client_company` int(11) DEFAULT NULL,
  `client_group` int(11) DEFAULT NULL,
  `client_contact` int(11) DEFAULT NULL,
  `role` int(11) DEFAULT NULL,
  `date_from` datetime DEFAULT NULL,
  `hourly_rate` decimal(18,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `rate` (`id`, `client_company`, `client_group`, 
                    `client_contact`, `role`, `date_from`, `hourly_rate`) 
VALUES
(4, NULL, NULL, NULL, 3, '2012-07-30 14:48:16', 115.00),
(5, 3, NULL, NULL, 3, '2012-07-30 14:51:38', 110.00),
(6, 3, NULL, NULL, 3, '2012-07-30 14:59:20', 112.00);
此表存储客户的计费费率;其想法是,在寻找工作角色的正确费率时,我们首先要寻找与给定角色和客户联系人相匹配的费率,然后如果找不到费率,则尝试将该角色与客户组(或“部门”)相匹配,然后是客户公司,最后只为该角色本身寻找全局费率。好的

费率可能会随着时间的推移而变化,因此表中可能包含多个与角色、公司、组和客户联系人的任何给定组合相匹配的条目:我需要一个查询,该查询只会为每个不同的组合返回最新的查询

考虑到这一点,而且这个话题似乎以各种形式频繁出现,我只能为我的迟钝道歉,并再次请某人解释为什么下面的查询返回上面的所有三条记录,而不是像我希望的那样,只返回ID为4和6的记录

这与我试图基于包含NULL的列进行连接有关吗

SELECT
    rate.*,
    newest.id
FROM rate
    LEFT JOIN rate AS newest ON(
        rate.client_company = newest.client_company
        AND rate.client_contact = newest.client_contact
        AND rate.client_group = newest.client_group
        AND rate.role= newest.role
        AND newest.date_from > rate.date_from
    )
WHERE newest.id IS NULL

FWIW,问题是连接空列。重要的缺失成分是聚结:

SELECT
    rate.*,
    newest.id
FROM rate
    LEFT JOIN rate AS newest ON(
        COALESCE(rate.client_company,1) = COALESCE(newest.client_company,1)
        AND COALESCE(rate.client_contact,1) = COALESCE(newest.client_contact,1)
        AND COALESCE(rate.client_group,1) = COALESCE(newest.client_group,1)
        AND COALESCE(rate.role,1) = COALESCE(newest.role,1)
        AND newest.date_from > rate.date_from
    )
WHERE newest.id IS NULL