我正在尝试获取每个用户的前 3 个兴趣,可能作为 LEFT JOIN 查询。
该应用程序的设计方式是,每个用户都有一组兴趣,这些兴趣只不过是表格的“孩子”(没有 的行parent
) 。categories
以下是一些带有模拟数据的简化表模式(请参阅SQL Fiddle 演示)
-- Users table
| ID | NAME |
--------------
| 1 | John |
| 2 | Mary |
| 3 | Chris |
-- Categories table -- Interests table
| ID | NAME | PARENT | | ID | USER_ID | CATEGORY_ID |
-------------------------------------- ------------------------------
| 1 | Web Development | (null) | | 1 | 1 | 1 |
| 2 | Mobile Apps | (null) | | 2 | 1 | 1 |
| 3 | Software Development | (null) | | 3 | 1 | 1 |
| 4 | Marketing & Sales | (null) | | 4 | 2 | 1 |
| 5 | Web Apps | 1 | | 5 | 2 | 1 |
| 6 | CSS | 1 | | 6 | 3 | 1 |
| 7 | iOS | 2 | | 7 | 3 | 1 |
| 8 | Streaming Media | 3 | | 8 | 3 | 1 |
| 9 | SEO | 4 |
| 10 | SEM | 4 |
为了获得给定用户的前 3 个兴趣,我通常执行以下查询:
SELECT `c`.`parent` as `category_id`
FROM `interests` `i` LEFT JOIN `categories` `c` ON `c`.`id` = `i`.`category_id`
WHERE `i`.`user_id` = '2'
GROUP BY `c`.`parent`
ORDER BY count(`c`.`parent`) DESC LIMIT 3
此查询返回categories
id = 2 的用户的前 3 个(父母)
我想了解如何查询 users 表并在 3 个不同的字段(首选)或group_concat(..)
一个字段中获取他们的前 3 个类别
SELECT id, name, top_categories FROM users, (...) WHERE id IN ('1', '2', '3');
有什么想法我应该怎么做?谢谢!