SQL 查询(不重复加入)

SQL query (Join without duplicates)

我有 tables userstopics。每个用户可以拥有 0 到多个主题(一对多关系)。

我如何才能只获得那些至少拥有一个主题的用户?

我需要来自用户的所有专栏(没有来自主题的专栏)并且 table users 中没有重复。在最后一列中,我需要主题数。

更新:

应该是这样的:

SELECT user.*, count(topic.id) 
FROM ad
LEFT JOIN topic ON user.id = topic.ad
GROUP BY user.id
HAVING count(topic.id) > 0;

但它需要 0 个结果。但它不应该是0.

使用内部联接和不同

select distinct user_table.id
from user_table 
inner join topics_table on topic_table.user_id = user_table.id
select u.id
, u.name
, count(b.topicName)
from user u
left join topic t on t.userid = u.id
group by u.id, u.name

首先你需要有你的两个 tables,因为你留下了关于你的 table 结构的有限信息我将用一个例子来解释它是如何工作的,然后你应该能够轻松将其应用到您自己的 tables.

首先你需要有两个 tables(你有)

Table "user"

id | name
1  | Joe Bloggs
2  | Eddy Ready

Table "topic"

topicid | userid | topic
      1 |      1 | Breakfast
      2 |      1 | Lunch
      3 |      1 | Dinner

现在要求对每个用户进行计数是使用以下方法完成的;

SELECT user.name, count(topic.topicid) 
FROM user
INNER JOIN topic ON user.id = topic.userid
GROUP BY user.name

如果您使用左联接,这将包括来自 "user" table 的记录,这些记录在 "topic" table 中没有任何行,但是如果您使用 INNER JOIN 这将只包括在两个 table 中具有匹配值的用户。

即因为主题中没有列出用户 ID“2”(我们用来加入)table,您不会得到该用户的任何结果。

希望对您有所帮助!

您可以 select 每个用户的主题编号,然后将其与用户数据结合起来。像这样:

with t as
(
select userid, count(*) as n
from topic
group by userid
)
SELECT user.*, t.n
FROM user
JOIN t ON user.id = t.userid