2010-10-19 103 views
1

我放棄了,現在我的JOIN針對搜索的原因視圖 - 我需要幫助:/MySQL的加入有3個表和空行

這裏是我的表:

型材

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 

我從這裏其他的答案在計算器幫助嘗試過,但不能得到它返回所有配置點。我不是一個大的MySQL專家爲人們所看到的一切,從上面的:)

回答

3

您需要使用LEFT連接。

喜歡的東西

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

+0

+1 Astander:貌似鏈接的用戶可能是一個INNER JOIN沒有任何抑制的配置文件? – richaux 2010-10-19 08:52:27

+0

這是偉大的,並按預期工作!非常感謝你!我不知道你可以像你一樣連接(?)JOIN。錯誤嘗試是非常困難的,這個大的查詢:)我現在要將它應用到我創建的另一個視圖! – 2010-10-19 09:34:25

+0

btw在WHERE子句中存在拼寫錯誤:第一個AND將會使查詢失敗 - 不知道您是否可以使用您的答案糾正此問題。 – 2010-10-19 09:35:48