如何从这个结构表中进行SQL查询?

时间:2016-12-07 10:40:15

标签: mysql sql sql-server

Initial:
1_ = country
2_ = gender 
3_ = purpose 

enter image description here

如何使SQL查询显示这样的数据

enter image description here

2 个答案:

答案 0 :(得分:0)

这或多或少会起作用:

SELECT user.id,
       user.name,
       country.code_name AS country,
       gender.code_name  AS gender,
       purpose.code_name AS purpose,
       visit.to_to
FROM   t_users        AS user
JOIN   t_user_details AS details
  ON   user.id = details.user_id
LEFT OUTER JOIN t_field_code AS country
             ON details.code = country.code
            AND country.code LIKE '1_%'
LEFT OUTER JOIN t_field_code AS gender
             ON details.code = gender.code
            AND gender.code LIKE '2_%'
LEFT OUTER JOIN t_field_code AS purpose
             ON details.code = purpose.code
            AND purpose.code LIKE '3_%'
LEFT OUTER JOIN t_visit_to AS visit
             ON user.id = visit.id_user
ORDER BY user.id;

唯一的问题是,如果用户有更多的访问位置,它会提供多行。

答案 1 :(得分:0)

尝试此操作(这是一种mysql方法),如果您想在SO中提问,请在下次发布带有文字而非图片的表格架构。

select
    u.id,
    u.name,
    max(case when ud.code like '1_%' then fc.code_name else '' end) as country,
    max(case when ud.code like '2_%' then fc.code_name else '' end) as gender,
    max(case when ud.code like '3_%' then fc.code_name else '' end) as purpose,
    group_concat(distinct vt.visit_to) as visit_to
from t_users u
left join t_user_details ud
on u.id = ud.id_user
left join t_field_code fc
on ud.code = fc.code
left join t_visit_to vt
on u.id = vt.id_user
group by u.id, u.name