0

这是我的查询:

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表还有一个包含 unix 时间戳的 int 字段,称为the_date.

问题是,表格dealer_name中最旧的行即将出现。assigns我想要表中带有的dealer_name最新行的。id_leadl.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>';
}

这可能吗?我真的太笨了,无法弄清楚这一点。

4

1 回答 1

1

只需将您的子查询用于 last_dealer 并进入您的联接并获取 max 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

(但不要使用 order by + limit,使用 max。)

于 2014-12-01T16:16:29.267 回答