【发布时间】:2017-12-12 00:16:29
【问题描述】:
这是我为每个城市/子类别组合获取第一行 $count 的查询
$contacts = $dbh->prepare("
SELECT *
FROM (SELECT c.*,
(@rn := IF(@cc = CONCAT_WS(':', city_id, subcategory_id), @rn + 1,
IF(@cc := CONCAT_WS(':', city_id, subcategory_id), 1, 1)
)
) as rn
FROM (SELECT reg.title as region_title, cnt.title, cnt.city_id, cnt.id, cnt.catalog_id, cnt.address, cnt.phone, cnt.email, cnt.website, cnt.subcategory_title, cnt.subcategory_id, cnt.manufacturer
FROM contacts as cnt
LEFT JOIN regions as reg
ON cnt.city_id = reg.id
WHERE city_id IN (".implode(',', $regions).") AND
subcategory_id IN (".implode(',', $categories).")
ORDER BY subcategory_title, city_id, title
) c CROSS JOIN
(SELECT @cc := '', @rn := 0) params
) c
WHERE rn <= $count");
我正在使用 $contacts->fetchAll(PDO::FETCH_GROUP); 按 reg.title 对行进行分组
[
['City 1'] = > [
[ contact 1 ],
[ contact 2 ],
...
],
['City 2'] = > [
[ contact 3 ],
[ contact 4 ],
...
]
...
]
现在我需要升级该查询,但它对我来说太复杂了 :( 所选行必须具有唯一的 contacts.catalog_id 值。
怎么做?
UPD
这是一个演示数据库 - http://sqlfiddle.com/#!9/ac71d7/2
【问题讨论】:
-
当我们说“唯一的contacts.catalog_id”值时,我们是否要从结果中排除任何和所有行,其中有多个行具有给定的
catalog_id?还是我们只是想确保catalog_id在结果中不重复?或者对于给定的(city_id,subcategory_id),catalog_id 没有重复?理解和传达规范是战斗的 80%。示例数据以及预期输出将大大有助于阐明规范。 -
我添加了一个示例数据。我们需要全局唯一的 catalog_id。