【问题标题】:Mysql : left join on variable tableMysql:在变量表上左连接
【发布时间】:2013-08-25 00:56:48
【问题描述】:

我遇到了一个复杂的 SQL 查询问题。

我有 3 张桌子: 用户, 用户类型1, 用户类型2

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

唯一可行的方法是连接两个表,但结果还包含来自错误表的所有空值...

我正在寻找一种方法来摆脱这些错误的字段,或者只对好表进行 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,只有 2 个字段:ID 和 Type。

其他表包含有关用户的详细信息。 user_type1 用于人。字段是姓名、年龄、...

user_type2 用于公司。字段包括姓名、法律形式、员工人数、...

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

如果 user.id 为 1 且 user.type 为 type1,我希望 mysql 从 user_type1 表中获取所有字段...

【问题讨论】:

  • user_type1_id,这是一个未命中的咒语吗? user_type1.id
  • @Deepanshu 是的,对不起。它是 user_type1.user_id。

标签: php mysql join conditional-statements


【解决方案1】:

你可以试试这个:-

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

【讨论】:

    【解决方案2】:

    那么你必须选择不为空的列:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 2018-10-14
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      相关资源
      最近更新 更多