如何内部加入一个查询表的MySQL查询?

时间:2019-06-07 19:54:39

标签: mysql sql

我需要使用以下两个表进行mysql查询的帮助:

个人资料(表1)

id  user_id gender  age height  bodytype
1   1         1     57    1        2
2   2         2     32    2        1

profile_lookup(表2)

id  option_group    option_value    option_name
1   gender                 1        Female
2   gender                 2        Male
3   gender                 3        Prefer not to say
4   height                 1        5 ft - 6  in
5   height                 2        5ft - 9 in
6   bodytype               1        Petite/slim
7   bodytype               2        Average

为简洁起见,我忽略了很多其他选项和选项值

我有兴趣使用如下所示的语法进行内部联接查询:

SELECT * 
  FROM profiles 
 WHERE bodytype = 2 
  JOIN profile_lookup 
    ON profiles.gender = profile_lookup..... (not sure)

通过以上两个表使用正确的语法请求帮助。谢谢

2 个答案:

答案 0 :(得分:1)

where子句应在JOIN子句之后

SELECT * FROM profiles 
INNER JOIN profile_lookup ON profiles.gender = profile_lookup.option_value    
 and profile_lookup.option_group   = 'gender' 
WHERE profiles.bodytype = 2 

对于联接,您需要适当的profile_lookup.option_value

答案 1 :(得分:1)

我想你想要

SELECT p.*, plg.option_name as gender
FROM profiles p INNER JOIN
     profile_lookup plg
     ON plg.option_group = 'gender' and
        plg.option_value = p.gender
WHERE p.bodytype = 2 ;

您可以将此扩展到其他列。如果某些值不匹配(例如LEFT JOIN),您可能需要NULL

SELECT p.*, plg.option_name as gender, plh.option_name as height
FROM profiles p LEFT JOIN
     profile_lookup plg
     ON plg.option_group = 'gender' AND
        plg.option_value = p.gender LEFT JOIN
     profile_lookup plh
     ON plh.option_group = 'height' AND
        plh.option_value = p.height
WHERE p.bodytype = 2