我必須加入用戶表中的 user_name,其中 user_profile 表中的 first_name 和 last_names。到這里為止一切都很好,但是當我嘗試從 user_role 表中獲取分配的各個角色時,它會為單個用戶提供多行,因為 1 個用戶可以擁有多個角色。
在嘗試申請時string_aggrole.names 時(以便多個角色在單個元組中顯示為逗號分隔),它在單獨的行中給出每個角色。
這是我試圖在 postgresql 中運行的示例查詢:
SELECT users.user_name, user_profiles.first_name, user_profiles.last_name,
(
SELECT string_agg (roles.name, ',')
from roles
where roles.id in (
select user_roles.role_id where users.id = user_roles.user_id
)
) as name
FROM users
JOIN user_profiles ON users.id = user_profiles.user_id
JOIN user_roles ON user_roles.user_id = users.id
uj5u.com熱心網友回復:
您必須使用GROUP BY子句才能將多個記錄聚合到一個組中。這與不必要的(我相信)嵌套 SQL 一起導致您得到錯誤的結果。
而是考慮以下內容:
SELECT users.user_name, user_profiles.first_name, user_profiles.last_name,
string_agg (roles.name, ',') as name
FROM users
JOIN user_profiles
ON users.id = user_profiles.user_id
JOIN user_roles
ON user_roles.user_id = users.id
JOIN roles ON user_roles.role_id = roles.id
GROUP BY users.user_name, user_profiles.first_name, user_profiles.last_name
uj5u.com熱心網友回復:
from您在最里面的子查詢中忘記了 a :
SELECT users.user_name,
user_profiles.first_name,
user_profiles.last_name,
(SELECT string_agg (roles.name, ', ')
from roles
where roles.id
in ( select u.role_id
from user_roles u --this was missing
where users.id = u.user_id)) as name
FROM users
JOIN user_profiles
ON users.id = user_profiles.user_id
-- JOIN user_roles --you're already getting roles in the innermost query
-- ON user_roles.user_id = users.id;
沒有它,該子查詢只是選擇一個當前行的role_id,而不是像您預期的那樣獨立獲取用戶的所有角色。看到這個演示。
請注意,一旦此問題得到解決,您還需要洗掉最后一個連接(在我的示例中已注釋掉)以避免為他們的每個角色增加用戶 - 無論如何您已經在最里面的子查詢中獲得了他們的角色。
使用常規的會更容易group by:
select users.user_name,
user_profiles.first_name,
user_profiles.last_name,
string_agg(roles.name,', ')
from users
inner join user_profiles
on users.id=user_profiles.user_id
inner join user_roles
on user_roles.user_id=users.id
inner join roles
on roles.id=user_roles.role_id
group by 1,2,3;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533849.html
上一篇:對于在兩個資料框中匹配的行,將列從一個資料框附加到另一個
下一篇:選擇加入同一張表
