在分组时通过显示连接的最旧结果来排序

时间:2014-12-01 13:34:57

标签: mysql subquery greatest-n-per-group groupwise-maximum

继承我的疑问:

select l.id, l.name, l.postcode, l.the_date, d.id as dealer_id, d.name as dealer_name,
(select count(`id`) from `lead_copies` where `id_lead`=l.id) as total_copies,
(select count(`id`) from `assigns` where `id_lead`=l.id) as total_assigns
from `leads` as l
left join `assigns` as a on a.id_lead = l.id
left join `dealers` as d on d.id = a.id_dealer
group by a.id_lead
order by l.the_date desc

assigns表还有一个int字段,其中包含名为the_date的unix时间戳。

问题是,dealer_name表中的最旧一行正在出现assigns。我想在dealer_name表格中id_lead l.id的最新行的assigns

我该怎么做?我无法弄明白。如果我将订单更改为a.the_date,我会得到不需要的结果,我希望这些结果按提前日期排序,而不是分配日期。如果有意义的话,我只想要在指定日期订购的经销商名称。

继续更好地了解我需要什么,但显然这个查询也不起作用:

select l.id, l.name, l.postcode, l.the_date, d.id as dealer_id, d.name as dealer_name,
(select count(`id`) from `lead_copies` where `id_lead`=l.id) as total_copies,
(select count(`id`) from `assigns` where `id_lead`=l.id) as total_assigns,
(select `id_dealer` from `assigns` where `id_lead`=l.id order by `id` desc limit 1) as last_dealer
from `leads` as l
left join `dealers` as d on d.id = last_dealer
order by l.the_date desc

最终编辑:我想要做的就是将以下内容合并为一个单一的SQL查询:

$sql = mysql_query("select l.id, l.name, l.postcode, l.the_date,
                    (select count(`id`) from `lead_copies` where `id_lead`=l.id) as total_copies,
                    (select count(`id`) from `assigns` where `id_lead`=l.id) as total_assigns
                    from `leads` as l
                    order by l.the_date desc");                     

while ($row = mysql_fetch_assoc($sql))
{
    $lead = array();

    foreach ($row as $k => $v)
        $lead[$k] = htmlspecialchars(stripslashes($v), ENT_QUOTES);

    $sql2 = mysql_query("select d.id as dealer_id, d.name as dealer_name
                        from `assigns` as a
                        left join `dealers` as d on d.id = a.id_dealer
                        where a.id_lead = ".$lead['id']."
                        order by a.the_date desc
                        limit 1");

    while ($row2 = mysql_fetch_assoc($sql2))
    {
        foreach ($row2 as $k2 => $v2)
            $lead[$k2] = htmlspecialchars(stripslashes($v2), ENT_QUOTES);               
    }

    echo '<pre>';
    print_r($lead);
    echo '</pre>';
}

这可能吗?我实在是太傻了,无法弄清楚这一点。

1 个答案:

答案 0 :(得分:1)

只需将您的子查询用于last_dealer并进入您的加入并最多使用the_date而不是id:

select l.id, l.name, l.postcode, l.the_date, d.id as dealer_id, d.name as dealer_name,
    (select count(`id`) from `lead_copies` where `id_lead`=l.id) as total_copies,
    (select count(`id`) from `assigns` where `id_lead`=l.id) as total_assigns,
    d.id as last_dealer
from `leads` as l
left join `dealers` as d
on d.id =
    (select `id_dealer` 
    from `assigns`
    where `id_lead`=l.id
    order by `the_date` desc
    limit 1)
order by l.the_date desc

(但不要使用+限制,使用最大值)