gpt4 book ai didi

mysql - 分组时通过显示最早的连接结果进行排序

转载 作者:行者123 更新时间:2023-11-29 12:32:45 24 4
gpt4 key购买 nike

这是我的查询:

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 表中最旧的行中。我想要 assigns 表中最新行的 dealer_name 以及 l.idid_lead。 p>

我该怎么做?我想不通。如果我将顺序更改为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

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

关于mysql - 分组时通过显示最早的连接结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27229621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com