具有这种简化的结构:
customers
-----------------------
id
name
salesagents_id (each client has their own sales agent assigned)
salesagents
-----------------------
id
name
visits
-----------------------
customers_id
salesagents_id
date
我需要获取所有客户的列表,以及另外三个字段:
这是我到目前为止的查询:
SELECT clients.*, salesagents.name, COUNT(v1.id) as visits_number, COUNT(v2.id) as visits_number_last_month
FROM `clients`
LEFT JOIN `salesagents` ON `clients`.`salesagents_id`=`salesagents`.`id`
LEFT JOIN `visits` as `v1` ON `clients`.`id` = `v1`.`clients_id`
LEFT JOIN `visits` as `v2` ON `clients`.`id` = `v2`.`clients_id` AND `v2`.`date` > FROM_UNIXTIME(UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH)))
GROUP BY `clients`.`id`
问题在于同一个桌面上的两个联接构成了两倍的访问次数。
我还能做什么?
答案 0 :(得分:2)
Distinct Count可以解决您的问题
{{1}}
答案 1 :(得分:1)
尝试使用SUM
和CASE WHEN
。第一个COUNT
计算所有访问者,第二个表达式仅在日期条件匹配时计算访问者。因此,如果条件适合,则使用CASE WHEN
表达式并添加1:
SELECT
clients.*
, salesagents.name, COUNT(v1.id) as visits_number
, SUM(
CASE WHEN `v1`.`date` > FROM_UNIXTIME(UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 MONTH)))
THEN 1
ELSE 0
END) as visits_number_last_month
FROM `clients`
LEFT JOIN `salesagents` ON `clients`.`salesagents_id`=`salesagents`.`id`
LEFT JOIN `visits` as `v1` ON `clients`.`id` = `v1`.`clients_id`
GROUP BY `clients`.`id`
答案 2 :(得分:1)
$prixActuels = $article->getArticlePlateforme()->first()->getPrixActuels();
$contenuLigne = array(
...
$article->getUniteAchatComplete(),
$prixActuels ? $prixActuels->first()->getPrixNet() : " ",
...
);