2013-08-22 94 views
0

我有一个复杂的SQL查询问题。Mysql:左连接变量表

我有3个表: 用户, user_type1, user_type2

我想请根据自己的类型的用户的详细信息。 我试着用CASE为LEFT JOIN动态选择表名,但是我失败了。 我也尝试过使用UNION,但似乎列必须相同。

是工作的唯一办法就是加入两个表,但后来的结果也包含错误的表中的所有空值...

我正在寻找一种方法来摆脱这些错误的字段,或者只为左右连接做好表格。

这里是我当前的代码:

SELECT 
    user.*, 
    user_type1.*, 
    user_type2.* 
FROM user 
LEFT JOIN user_type1 
    ON user_type1.user_id = user.id 
LEFT JOIN user_type2 
    ON user_type2.user_id = user.id 
AND user.id = 1 

通常我只会做非常简单的查询,所以我有点糊涂了。谢谢,如果你能帮助我。

编辑: 主表是用户,只有2个字段:ID和类型。

其他表包含有关用户的详细信息。 user_type1适用于人。这些字段是名称,年龄,...

user_type2是针对公司。这些字段是名称,法律形式,雇员人数,...

所以我只知道用户表中的ID,我需要获得良好表的字段。

如果user.id是1和user.type是TYPE1,我希望MySQL得到user_type1表中的所有字段...

+0

user_type1_id,它是一个小姐拼? user_type1.id –

+0

@Deepanshu是的,对不起。它是user_type1.user_id。 – FLX

回答

0

则必须选择不null作为列:

SELECT 
    user.*, 
    user_type1.*, 
    user_type2.* 
FROM user 
LEFT JOIN user_type1 
    ON user_type1_id = user.id 
LEFT JOIN user_type2 
    ON user_type2.user_id = user.id 
AND user.id = 1 
AND table.column_name IS NOT NULL 
2

你可以试试这个: -

select * 
from user, user_type1, user_type2 
where user_type1.user_id = user.id and user_type2.user_id = user.id AND user.id = 1