如何基于其他表列选择列?

时间:2019-06-05 18:13:50

标签: mysql sql

我有两个表:Table1和Table2。 这两个表都在下面给出:

这里是table1

+----+----------+
| id | t1_title |
+----+----------+
| 1  | AAA      |
+----+----------+
| 2  | BBB      |
+----+----------+
| 3  | CCC      |
+----+----------+

这里是table2

+----+----------+--------+
| id | t2_title | t1_IDs |
+----+----------+--------+
| 1  | John     | 1,3    |
+----+----------+--------+
| 2  | Sam      | 2      |
+----+----------+--------+
| 3  | Monty    | 1,2    |
+----+----------+--------+
| 4  | Rose     | 2,3    |
+----+----------+--------+

现在我想基于table1.title获取table2.t1_IDs(如AAA,BBB,CCC),如下所示:

+----+----------+-----------+
| id | t2_title | t1_titles |
+----+----------+-----------+
| 1  | John     | AAA,CCC   |
+----+----------+-----------+
| 2  | Sam      | BBB       |
+----+----------+-----------+
| 3  | Monty    | AAA,BBB   |
+----+----------+-----------+
| 4  | Rose     | BBB,CCC   |
+----+----------+-----------+

1 个答案:

答案 0 :(得分:1)

SELECT  a.id,
        t2_title,
        GROUP_CONCAT(b.t1_title ORDER BY b.id)
FROM    table2 a
        INNER JOIN table1 b
            ON FIND_IN_SET(b.t1_title, a.t1_IDs) > 0
GROUP   BY a.id,a.t2_title

db-fiddle