我有以下表格:
1) tbl_entries :
+----------+-------------+-------------------+
| entry_id | entry_title | entry_category_id |
+----------+-------------+-------------------+
| 10 | Entry 1 | 3 |
| 20 | Entry 2 | 2 |
| 30 | Entry 3 | 2 |
| 40 | Entry 4 | 5 |
+----------+-------------+-------------------+
2) tbl_categories
+-------------+---------------+
| category_id | category_name |
+-------------+---------------+
| 1 | Animal |
| 2 | People |
| 3 | Gadgets |
| 4 | Entertainment |
| 5 | Business |
+-------------+---------------+
2) tbl_categories_secondary
+-------------+---------------+
| cs_entry_id | cs_category_id|
+-------------+---------------+
| 10 | 5 |
| 20 | 1 |
| 20 | 3 |
| 20 | 5 |
| 40 | 1 |
| 40 | 4 |
+-------------+---------------+
我想查询所有条目及其主要和次要类别( 按字母顺序排列并以逗号分隔 ),这样会导致:
+-------------+---------------------------------+
| title | categories |
+-------------+---------------------------------+
| Entry 1 | Business,Gadgets |
| Entry 2 | Animal,Business,Gadgets,People |
| Entry 3 | People |
| Entry 4 | Animal,Business,Entertainment |
+-------------+---------------------------------+
这是我几乎一天没有运气的尝试:
SELECT tbl_entries.entry_title AS title, addCats.more_categories AS categories
FROM tbl_entries,
(
SELECT cs_entry_id, GROUP_CONCAT(category_name SEPARATOR ',') AS more_categories
FROM tbl_categories
INNER JOIN tbl_categories_secondary
ON tbl_categories.category_id = tbl_categories_secondary.cs_category_id
GROUP BY cs_entry_id
) addCats
INNER JOIN categories
ON tbl_entries.entry_category_id = tbl_categories.category_id
我现在的问题是如何获取条目的主要和所有次要类别,并将它们混合/放入一列,如上所述。
任何帮助将不胜感激:)
答案 0 :(得分:0)
尝试类似下面的内容。为tbl_categories创建别名为tc1并加入
选择tbl_entries.entry_title,concat(group_concat(tbl_categories.category_name),group_concat(tc1.category_name)) tbl_entries.entry_category_id = tbl_categories.category_id上的内连接tbl_categories tbl_categories_secondary.cs_entry_id = tbl_entries.entry_id上的内连接tbl_categories_secondary 内联接tbl_categories为tc1 on tc1.category_id = tbl_categories_secondary.cs_category_id group by tbl_entries.entry_title