在subselect中使用GROUP_CONCAT的Mysql

时间:2014-08-04 13:58:13

标签: mysql sql select group-concat subquery

我在mysql中遇到subselect问题。在餐馆餐厅,我有字段“sup”,其中我用逗号分隔ID。 基本选择:

mysql> select name, sup from restaurants LIMIT 5;
+-------------------------------------+---------+
| name                                | sup     |
+-------------------------------------+---------+
| Pizzerija in špagetarija Buf        | 2,14,18 |
| EJGA - KAVARNA - RESTAVRACIJA - PUB | 11,17   |
| Restavracija Center                 | 5,22    |
| Restavracija Viola                  | 5,13,17 |
| Gostilna Anderlič                   | 5,17    |
+-------------------------------------+---------+
5 rows in set (0.00 sec)

我想知道sup.restaurants表中的ID表中的字段“SI”。所以我的选择是:

mysql> SELECT GROUP_CONCAT(suply.SI SEPARATOR ', ')  FROM `suply` WHERE id IN (2,14,18);
+---------------------------------------+
| GROUP_CONCAT(suply.SI SEPARATOR ', ') |
+---------------------------------------+
| Italijanska, Špagetarija, Picerija    |
+---------------------------------------+
1 row in set (0.00 sec)

所以我用subselct编写了select,但效果不好:

mysql> SELECT restaurants.name,
    -> (SELECT GROUP_CONCAT(suply.SI SEPARATOR ', ')  FROM `suply` WHERE id IN (restaurants.sup)) AS hrana
    ->  FROM restaurants
    ->  LIMIT 5;
+-------------------------------------+--------------------+
| name                                | hrana              |
+-------------------------------------+--------------------+
| Pizzerija in špagetarija Buf        | Italijanska        |
| EJGA - KAVARNA - RESTAVRACIJA - PUB | Mednarodna kuhinja |
| Restavracija Center                 | Slovenska domača   |
| Restavracija Viola                  | Slovenska domača   |
| Gostilna Anderli?                   | Slovenska domača   |
+-------------------------------------+--------------------+
5 rows in set (0.00 sec)

为什么在这个选择中我只得到第一个字符串?

1 个答案:

答案 0 :(得分:0)

使用FIND_IN_SET功能搜索逗号分隔列表

WHERE FIND_IN_SET(id, restaurants.sup)