这是我的查询:

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_nameid_lead表中l.idassigns

我该怎么做呢?我不知道。如果我将订单更改为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


最终编辑:我要做的就是将以下内容合并为1个单个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>';
}


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

最佳答案

只需对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


(但不要按+限制使用订单,而要使用最大值。)

09-15 18:11