【发布时间】:2012-03-06 04:09:23
【问题描述】:
我已经考虑这个问题有一段时间了,我认为最好四处打听,听听其他人的想法。
我正在构建一个在 Mysql 上存储位置的系统。每个位置都有一个类型,有些位置有多个地址。
表格看起来像这样
location
- location_id (autoincrement)
- location_name
- location_type_id
location_types
- type_id
- type_name (For example "Laundry")
location_information
- location_id (Reference to the location table)
- location_address
- location_phone
因此,如果我想查询数据库中最近添加的 10 个,我会使用以下内容:
SELECT l.location_id, l.location_name,
t.type_id, t.type_name,
i.location_address, i.location_phone
FROM location AS l
LEFT JOIN location_information AS i ON (l.location_id = i.location_id)
LEFT JOIN location_types AS t ON (l.location_type_id = t.type_id)
ORDER BY l.location_id DESC
LIMIT 10
对吗?但问题是,如果一个位置有超过 1 个地址,则限制/分页将不准确,除非我“GROUP BY l.location_id”,但这将只显示每个地方的一个地址.. 会发生什么有多个地址的地方?
所以我认为解决这个问题的唯一方法是在循环中进行查询。像这样的东西(伪代码):
$db->query('SELECT l.location_id, l.location_name,
t.type_id, t.type_name
FROM location AS l
LEFT JOIN location_types AS t ON (l.location_type_id = t.type_id)
ORDER BY l.location_id DESC
LIMIT 10');
$locations = array();
while ($row = $db->fetchRow())
{
$db->query('SELECT i.location_address, i.location_phone
FROM location_information AS i
WHERE i.location_id = ?', $row['location_id']);
$locationInfo = $db->fetchAll();
$locations[$row['location_id']] = array('location_name' => $row['location_name'],
'location_type' => $row['location_type'],
'location_info' => $locationInfo);
}
现在我得到了最后 10 个位置,但这样做我最终得到了至少 10 个查询,而且我认为这对应用程序性能没有帮助。
有没有更好的方法来实现我正在寻找的东西? (准确的分页)。
【问题讨论】:
-
您要返回哪个地址(local_information 记录)以获得位置?如果你能说出你想要哪一个,我们就可以告诉计算机你想要哪一个。
标签: php mysql performance