Mysql SQL:如果不在表中,则联接或仅选择一行

Mysql SQL:如果不在表中,则联接或仅选择一行,mysql,sql,database,Mysql,Sql,Database,我有四个表:一个是用户,一个是配置文件(用户配置文件),一个是配置文件和内容之间的关系,还有一个是内容。该内容表不能有任何条目,用户配置文件可以有单个条目或多个条目 我希望获得所有在内容表中没有条目的用户,或者如果他们有多个条目,则只获得一个条目 以下是我当前的SQL: SELECT users.uid AS uid, profile.id AS profile_id, content.id AS content_id FROM users users_data LEFT JOIN profi

我有四个表:一个是用户,一个是配置文件(用户配置文件),一个是配置文件和内容之间的关系,还有一个是内容。该内容表不能有任何条目,用户配置文件可以有单个条目或多个条目

我希望获得所有在内容表中没有条目的用户,或者如果他们有多个条目,则只获得一个条目

以下是我当前的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
我尝试添加简单的连接,以便从内容表中只获得一个结果,而且效果很好。但是有了它,我就不会得到内容表中没有条目的用户

我已经被困了几个小时,尝试了很多事情。。。提前感谢您的帮助

编辑:

用户示例

id
8
9
10
配置文件示例:

id uid
2000 8
2001 9
2002 10
id pid content_id
1 2000 100
2 2001 101
3 2001 102
id uid
100 8
101 9
102 9 
内容\u用于\u配置文件示例:

id uid
2000 8
2001 9
2002 10
id pid content_id
1 2000 100
2 2001 101
3 2001 102
id uid
100 8
101 9
102 9 
内容示例:

id uid
2000 8
2001 9
2002 10
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
您不应该在没有aggregation函数的情况下使用groupby。此已弃用的数据库最多,在最新版本的mysql中不允许使用

a 对于仅获取内容值的一个条目,可以使用aggreation函数,例如min()…max()


向我们展示一些示例表数据和预期结果-所有内容都是格式化文本,而不是图像。首先看一看。好的,我正在创建一些虚假数据,不久将编辑我的帖子!子查询上的
连接
是否也需要是
左连接
?(因为它正在连接到一个本身已被
左连接的表?)我刚刚尝试了这两种方法,第一种方法没有返回任何结果。第二个返回的结果与mine@rob-art然后更新您的问题添加适当的数据样本和预期结果。@rob art answer更新删除子查询上的(无用)联接。。您使用联接添加的子查询没有用处。。只需产生更多的行,重复您真正需要的。。在我的回答中,第一个查询检索内容表中具有null值的行..检查null值..第二个查询使用min(…)和groupby来减少行数,返回仅为内容结果选择min(值)。。希望是明确的