一對多業務關系分頁查詢,多端作為查詢條件
業務關系為一對多時,多端可以作為查詢條件并分頁顯示,下面提供兩種設計思路:
方法一
使用兩張表,一張存儲用戶信息,另一張存儲對應標簽:
-
user表:
| user_id | name | |---------|------| | 1 | 小明 | | 2 | 小李 | | 3 | 小張 |
-
tag表:
| tag_id | user_id | tag | |---------|---------|-------| | 1 | 1 | 活潑 | | 2 | 1 | 可愛 | | 3 | 2 | 活潑 | | 4 | 3 | 可愛 |
此方法存在如下問題:
- 以stream流對name進行分組,性能會因數據量增大而下降。
- 若以tag作為查詢條件,會漏掉其他相關tag。
方法二
采用單表設計,將標簽信息存儲在同一列中:
-
user表:
| user_id | name | tags | |---------|------------|--------------| | 1 | 小明 | 活潑, 可愛 | | 2 | 小李 | 活潑 | | 3 | 小張 | 可愛 |
此方法可以解決上述問題:
- 單表查詢避免了流分組的性能開銷。
- 使用exists子查詢可以準確篩選滿足查詢條件的數據。
分頁查詢sql:
select *, (select group_concat(tag) from tag where user_id = user.id and tag = '活潑') as tags from user where exists(select 1 from tag where user_id = user.id and tag = '活潑' limit 1) limit 0, 10;
最終結果:
| user_id | name | tags | |---------|------------|--------------| | 1 | 小明 | 活潑, 可愛 |
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END