我希望有人可以帮我解决这个问题.
假设我有3个DB表:
Users:
user_id, user_name
100, John
101, Jessica
Cars:
car_id, car_name
30, Corvette
31, BMW
UsersCars:
user_id, car_id, car_colour
100, 30, Red
101, 30, Green
101, 31, Green
(so John got a red corvette and Jessica has a green Corvette and a BMW)
Run Code Online (Sandbox Code Playgroud)
我想有代码返回一个多维PHP数组,如:
Array
(
[100] => Array
(
[user_id] => 100
[user_name] => John
[cars] => Array
(
[car_id]=>30,
[car_name]=>'Corvette',
[car_colour]=>'Red'
)
)
[101] => Array
(
[user_id] => 101
[user_name] => Jessica
[cars] => Array
( …Run Code Online (Sandbox Code Playgroud) php mysql performance associative-array multidimensional-array
有2张桌子:
users
==========
id
name
notes
=========
id
user_id
note
Run Code Online (Sandbox Code Playgroud)
用户可以有多个笔记。
我想做一个 SQL 查询,获取所有用户的所有字段以及注释数量。此外,我希望结果按注释数量排序(描述)
我写了这个,但我想知道这是否是解决这个问题的正确/最快的方法:
SELECT u.*, count(n.id) as amountnotes FROM users AS u
LEFT JOIN notes AS n ON u.id=n.user_id
GROUP BY u.id
ORDER BY amountnotes DESC
Run Code Online (Sandbox Code Playgroud)
EXPLAIN给了我 2 个结果。用户上的“使用临时;使用文件排序”和注释上的“使用where;使用连接缓冲区(块嵌套循环)”
任何帮助表示赞赏,谢谢。如果建议采用不同的方法,请解释原因,以便我能够理解。