如何从一个表中限制为1的多个表中选择数据

时间:2016-08-01 07:04:55

标签: mysql

我有多个复选框,用户可以将教育数据添加到数据库。我的结构看起来跟在数据库中:我有三个表,user_education,我保持记录用户选择的教育级别(它可以有多个行为同一个user_id),教育,我存储用户教育描述(只有一行)每user_id),以及我存储所有学位的教育水平。

user_education

id | user_id | education_id
1    83        1
2    83        2

education_description

user_id | description
83        test

education_levels

education_id | education
1              alusharidus
2              keskharidus
3              Bachelor’s degree
4              Master’s degree

等等。我的问题是如何为特定用户选择所有数据,但只显示一次描述?

我试过这个:

select
    user_education.education_id,
    education_levels.education,
    education_description.description
from
    user_education
        join education_description
        left join education_levels
            on user_education.education_id=education_levels.education_id and education_description.user_id = user_education.user_id WHERE user_education.user_id=83;

给了我这个:

enter image description here

这里是多次插入的描述,但我想只有一次。我的结构对于这种类型的逻辑是错误的吗?如果没有,我怎么才选择它一次,所以我可以在提交表格后为用户附加数据?

修改

添加所需的结果

education_description

user_id | education | description
83        test        testing
83        test2
83        test3

1 个答案:

答案 0 :(得分:2)

请你试试这个答案: -

select
    user_education.education_id,
    GROUP_CONCAT(education_levels.education separator ' ,'),
    education_description.description
from
    user_education
        join education_description
        left join education_levels
            on user_education.education_id=education_levels.education_id and education_description.user_id = user_education.user_id 
WHERE user_education.user_id=83 
GROUP BY user_education.user_id;