使用MYSQL,我有2个表:联系人和类别
+------+---------+
| id | title |
+------+---------+
| 10 | Cat |
| 11 | John |
| 12 | Sam |
+------+---------+
和类别
+------+------------+----------+
| id | id_contact | category |
+------+------------+----------+
| 1 | 10 | C# |
| 2 | 10 | WPF |
| 3 | 11 | PHP |
| 4 | 11 | JQuery |
| 5 | 12 | MySQL |
| 6 | 12 | MSSQL |
| 7 | 12 | PHP |
+------+------------+----------+
我想选择所有具有PHP类别的联系人,在这种情况下,选择结果将是:
+------+---------+---------------------+
| id | title | categories |
+------+---------+---------------------+
| 11 | John | PHP , JQuery |
| 12 | Sam | MySQL , MSSQL , PHP |
+------+---------+---------------------+
包含一个列,其中包含连接并用“,”分隔的所有类别。 请建议。
答案 0 :(得分:1)
首先加入两个表,使用MySQL的GROUP_CONCAT()
来连接行。
SELECT a.ID, a.Title,
GROUP_CONCAT(b.category) categories
FROM Contacts a
INNER JOIN categories b
ON a.ID = b.id_contact
GROUP BY a.ID, a.Title
HAVING SUM(b.category = 'php') > 0
此条件HAVING SUM(b.category = 'php') > 0
仅过滤类别中至少有php
条记录的记录。