簡體   English   中英

SQL:如果不在表中則聯接或僅選擇一行

[英]SQL : join if not in table or select only one row

我有四個表:一個用戶,一個配置文件(用戶配置文件),一個配置文件和內容之間的關系以及一個內容。 該內容表可能沒有條目,用戶配置文件只能有一個條目或多個條目。

我想讓所有在內容表中沒有條目的用戶,或者如果他們有多個條目,則只獲得一個。

這是我當前的SQL:

SELECT
users.uid AS uid,
profile.id AS profile_id,
content.id AS content_id
FROM 
users users_data
LEFT JOIN profile profile_data ON users_data.id = profile_data.uid
LEFT JOIN content_for_profile content_profile ON profile_data.id = content_profile.pid
LEFT JOIN content content_data ON content_for_profile.content_id = content_data.id
JOIN (
SELECT content_data_join.id, content_data_join.uid
FROM content content_data_join
GROUP BY content_data_join.uid
) content_data_join ON content_for_profile.content_id=content_data_join.id
GROUP BY uid, profile_id, content_id
ORDER BY profile.created DESC

我試圖添加簡單的JOIN以僅從內容表中獲得一個結果,並且它可以工作。 但是,那樣一來,我不會在內容表中沒有沒有條目的用戶。

我已經被困了幾個小時了,嘗試了很多事情……在此先感謝您的幫助!

編輯:

用戶實例

id
8
9
10

個人資料示例:

id uid
2000 8
2001 9
2002 10

content_for_profile示例:

id pid content_id
1 2000 100
2 2001 101
3 2001 102

內容示例:

id uid
100 8
101 9
102 9 

預期結果 :

uid profile_id content_id
8 2000 100
9 2001 101
10 2002 NULL

為了使用戶無需在內容表中輸入內容,可以使用where條件為null

    SELECT
    users.uid AS uid,
    profile.id AS profile_id,
    content.id AS content_id
    FROM 
    users users_data
    LEFT JOIN profile profile_data ON users_data.id = profile_data.uid
    LEFT JOIN content_for_profile content_profile ON profile_data.id = content_profile.pid
    LEFT JOIN content content_data ON content_for_profile.content_id = content_data.id

    where content_data.id is null  

    ORDER BY profile.created DESC

如果沒有聚集功能,則不應使用GROUP BY。 這個不推薦使用的是大多數數據庫,並且在最新版本的mysql中是不允許的

一個只獲取一個條目的內容值,您可以使用聚合函數,例如min()..max()

    SELECT
    users.uid AS uid,
    profile.id AS profile_id,
    min(content.id) AS content_id
    FROM 
    users users_data
    LEFT JOIN profile profile_data ON users_data.id = profile_data.uid
    LEFT JOIN content_for_profile content_profile ON profile_data.id = content_profile.pid
    LEFT JOIN content content_data ON content_for_profile.content_id = content_data.id

    GROUP BY users.uid ,profile.id 
    ORDER BY profile.created DESC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM