繁体   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