有联接时如何从多个表中选择?

时间:2019-05-01 19:22:00

标签: sql postgresql

我有一个当前查询,该查询为我提供了一个用户ID和计数表,但我希望该表更具描述性。此查询工作正常:

SELECT a.user_id, count(*) FROM table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE <some condition>
    AND <some condition>
    AND b.account_created_at < a.account_created_at
GROUP BY a.user_id
ORDER BY count DESC;

但是,我想在输出中添加字段,但是这样做很麻烦:

SELECT a.user_id, b.organization, b.first_name, b.last_name, b.alias, count(*) FROM table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE <some condition>
    AND <some condition>
    AND b.account_created_at < a.account_created_at
GROUP BY a.user_id
ORDER BY count DESC;

但是我得到一个错误,提示b.organization must appear in the GROUP BY clause or be used in an aggregate function

基本上,作为输出,我想要:

organization | first_name | last_name | alias | user_id | id_counts

除了最后两列之外的所有列都来自table_b

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您需要列不在分组依据的聚合功能中

SELECT a.user_id, b.organization, b.first_name, b.last_name, b.alias, count(*) 
FROM table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE <some condition>
    AND <some condition>
    AND b.account_created_at < a.account_created_at
GROUP BY a.user_id, b.organization, b.first_name, b.last_name, b.alias
ORDER BY count DESC;

或为这些列添加聚合功能

SELECT a.user_id, max(b.organization), max(b.first_name), max(b.last_name), max(b.alias), count(*) 
FROM table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE <some condition>
    AND <some condition>
    AND b.account_created_at < a.account_created_at
GROUP BY a.user_id, b.organization, b.first_name, b.last_name, b.alias
ORDER BY count DESC;

答案 1 :(得分:0)

除了count之外,select部分中的所有项目也应按查询分组。

SELECT a.user_id, b.organization, b.first_name, b.last_name, b.alias, count(*) FROM 
table_a a
JOIN table_b b ON b.user_id = a.user_id
WHERE <some condition>
AND <some condition>
AND b.account_created_at < a.account_created_at
GROUP BY a.user_id,b.organization, b.first_name, b.last_name, b.alias
ORDER BY count DESC