1

使用 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 |
+------+---------+---------------------+

有一列包含所有由 "," 连接和分隔的类别。请指教。

4

1 回答 1

1

首先加入两个表,然后使用 MySQLGROUP_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至少有 1 条记录的记录。php

于 2013-09-12T15:54:56.993 回答