假设数据库表与此类似(至少,它们应该以这种方式规范化):
city ( id, name );
category ( id, name );
rating ( city_id, category_id, rating );
...具有与此类似的一系列兴趣:
$interests = array(
'Food',
'Shopping'
);
...以下sql:
$sql = 'SELECT
city.name as city,
GROUP_CONCAT( category.name || ": " || rating.rating, ", " ) as ratings,
SUM( rating.rating ) as totalRating
FROM
rating
JOIN
city
ON city.id = rating.city_id
JOIN
category
ON category.id = rating.category_id
WHERE
category.name IN( ' . implode( ',', array_map( array( $db, 'quote' ), $interests ) ) . ' )
GROUP BY
city.name
ORDER BY
totalRating DESC';
(我假设在这里使用PDO
,用于转义,但是用你的 mysql 库提供的任何引用/转义机制PDO::quote()
替换回调)array( $db, 'quote' )
... 将产生与此类似的结果集(我已经为我的示例填充了随机评级数据):
array (
0 => array (
'name' => 'Chicago',
'ratings' => 'Food: 3, Shopping: 3',
'totalRating' => '6'
),
1 => array (
'name' => 'New York',
'ratings' => 'Food: 1, Shopping: 4',
'totalRating' => '5'
),
2 => array (
'name' => 'Seattle',
'ratings' => 'Food: 4, Shopping: 1',
'totalRating' => '5'
),
3 => array (
'name' => 'Los Angeles',
'ratings' => 'Food: 2, Shopping: 2',
'totalRating' => '4'
),
4 => array (
'name' => 'Boston',
'ratings' => 'Food: 1, Shopping: 2',
'totalRating' => '3'
),
5 => array (
'name' => 'San Francisco',
'ratings' => 'Food: 1, Shopping: 1',
'totalRating' => '2'
)
)
如果您只需要第一个结果,请附加LIMIT 1
到 sql 查询。
这应该让你知道如何去完成你想要的。
最重要的是:让 MySQL 完成所有工作(过滤、排序)——而不是 PHP。