我有一个复杂的SQL查询问题。
我有三张桌子:使用者user_ type1,user_type2
我试图根据用户的类型来选择用户的详细信息。我尝试使用CASE为LEFT JOIN动态选择表名,但失败了。我也尝试过使用UNION,但似乎列必须是相同的。
唯一有效的方法是连接这两个表,但结果也包含错误表中的所有null值。。。
我正在寻找一种方法来消除这些错误的字段,或者只对好的表执行LEFT JOIN。
这是我当前的代码:
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
通常我只做非常简单的查询,所以我有点困惑。如果你能帮我的话,谢谢。
编辑:主表是user,只有两个字段:ID和Type。
其他表包含有关用户的详细信息。user_type1是为人们准备的。字段为姓名、年龄。。。
user_type2适用于公司。字段包括姓名、法定形式、员工人数。。。
所以我只知道用户表中的ID,并且我需要获得好表的字段。
如果user.id是1,user.type是type1,我希望mysql从user_type1表中获取所有字段。。。
你可以试试这个:-
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
则必须选择非空列作为:
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