[英]How to query without doing N+1 query in MySQL
我有2張桌子
users_table
id | first_name
1 | first name1
2 | first name2
addresses_table
id | user_id | address
1 | 1 | first address of user 1
2 | 1 | second address of user 1
3 | 2 | first address of user 2
4 | 2 | second address of user 2
我想要這樣的表結果,第一列是users_table first_name,第二列是每個用戶的愛好,用逗號分隔
<table>
<tr>
<td>first name1</td><td>first address of user 1, second address of user 1</td>
</tr>
<tr>
<td>first name2</td><td>first address of user 2, second address of user 2</td>
</tr>
</table>
如果我必須查詢,則必須select * from users_table
然后select * from addresses_table where user_id = 1
獲取每個用戶的地址,例如select * from addresses_table where user_id = 1
fromaddressstable,這不是很有效,可以使用ORM來防止,但是我想知道我們可以防止N使用SQL +1查詢
您可以使用以下查詢
從用戶表usrTable中選擇first_name,group_concat(address,',')作為地址usrTable.id = addTable.user_id上的組由first_name組成的addressstable addTable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.