【问题标题】:MySQL Join with 3 tables and empty rowsMySQL加入3个表和空行
【发布时间】:2010-10-19 08:29:24
【问题描述】:

由于搜索原因,我现在放弃我的 JOIN 创建视图 - 我需要帮助:/

这是我的桌子:

个人资料

id   company    user_id
1    ACME       2
2    Joe        4
3    Wolf       5

用户

id   role_id   online
2    4         2010-10-08
4    2         2010-10-08
5    4         2010-10-08

评分标准

id    title
1     Steel
2     Stone
3     Wood

Profiles_Rubrics

profile_id   rubric_id
1            1
1            2
2            3
2            1

我想从这些表中获得一个视图,其中每个配置文件都有一行 - 还包括在 HABTM Profiles_Rubrics 中没有条目的配置文件。现在我只能获取在 HABTM 表中有条目的配置文件:

CREATE OR REPLACE VIEW Catalog_Branches AS
SELECT
  profiles.id,
  profiles.company,
  GROUP_CONCAT(DISTINCT CAST(rubrics.id AS CHAR) SEPARATOR ', ') AS rubric,
  GROUP_CONCAT(DISTINCT CAST(rubrics.title AS CHAR) SEPARATOR ', ') AS rubric_title,
  profiles.user_id
FROM
  profiles,
  profiles_rubrics 
    JOIN rubrics ON profiles_rubrics.rubric_id=rubrics.id,
  users
WHERE
  profiles_rubrics.profile_id=profiles.id
  AND profiles_rubrics.rubric_id=rubrics.id
  AND users.id=profiles.user_id
  AND users.profile_online IS NOT NULL
  AND users.role_id!=1
GROUP BY
  profiles.id

我在 stackoverflow 的其他答案的帮助下尝试了它,但无法到达返回所有配置文件的地步。从上面的所有内容中可以看出,我不是 MySQL 专家 :)

【问题讨论】:

    标签: mysql join rows has-and-belongs-to-many


    【解决方案1】:

    您需要使用 LEFT JOINS。

    类似

    SELECT 
      profiles.id, 
      profiles.company, 
      GROUP_CONCAT(DISTINCT CAST(rubrics.id AS CHAR) SEPARATOR ', ') AS rubric, 
      GROUP_CONCAT(DISTINCT CAST(rubrics.title AS CHAR) SEPARATOR ', ') AS rubric_title, 
      profiles.user_id 
    FROM 
      profiles LEFT JOIN
      profiles_rubrics  ON  profiles_rubrics.profile_id=profiles.id LEFT JOIN
      rubrics   ON  profiles_rubrics.rubric_id=rubrics.id LEFT JOIN
      users ON  users.id=profiles.user_id 
    WHERE 
      users.profile_online IS NOT NULL 
      AND users.role_id!=1 
    GROUP BY 
      profiles.id 
    

    看看SQL Joins

    【讨论】:

    • +1 Astander:看起来指向用户的链接可能是 INNER JOIN 而不抑制任何配置文件?
    • 这很棒并且可以按预期工作!非常感谢你!我不知道你可以像你一样连接 (?) JOIN。对于这个大查询,错误地尝试是非常困难的 :) 我现在要把它应用到我正在创建的另一个 VIEW 中!
    • 顺便说一句,WHERE 子句中有一个错字:第一个 AND 将使查询失败 - 不知道您是否可以使用您的答案为即将到来的用户更正此问题。
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2012-07-16
    相关资源
    最近更新 更多