我如何在MySql中制作这种Select?

时间:2015-06-07 01:07:12

标签: mysql select-query

我有一张桌子,看起来像这样,

mysql> select * from match_info;
+---------------+---------+------------+-------------+-----------+
| match_info_id | user_id | body_types | hair_colors | ethnicity |
+---------------+---------+------------+-------------+-----------+
|             1 |       1 | 1,5,9,13   | 1,5,9,13    | 2,6,10    |
|             2 |       2 | 1,5,9,13   | 5           | 1,5,9     |
+---------------+---------+------------+-------------+-----------+

我使用了body_typeshair_colorsethnicity的查找表,每个表中都有idname列。

使用上面我需要为特定用户选择所有值。像这样。

来自body_type表。

身体类型:Skinny, Muscular, Large, Ripped

头发颜色:Blonde, Dark Brown, Strawberry Blonde, Dark Blonde等......

任何人都可以告诉我如何进行选择查询以获得上述结果。

希望有人可以帮助我。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以加入表并将find_in_set函数放在on子句中。 试试这个:

select t.match_info_id, t.user_id,
    group_concat(distinct a.name) as body_types,
    group_concat(distinct b.name) as hair_colors,
    group_concat(distinct c.name) as ethnicity
from match_info as t
    inner join body_type as a on find_in_set(a.id,t.body_types)
    inner join hair_color as b on find_in_set(b.id,t.hair_colors)
    inner join ethnicity as c on find_in_set(c.id,t.ethnicity)
group by t.match_info_id, t.user_id

请注意,根据您的需要,您可以使用left join代替inner join