我正在尝试从数据库中提取所有客户信息。 我需要为用户获取所有地址。
我有一个用户表和地址表。地址表为每个用户保存0个地址。我需要加入现有查询的每个用户的所有地址,我不介意每个地址重复的用户信息。
到目前为止,我有这个查询,它返回所有客户数据,与区域表一起获取货币名称,然后与订单联系以获得该用户的已发货订单总数。
SELECT ( CASE
WHEN u.password IS NULL THEN 'GUEST'
ELSE 'CUSTOMER'
END ) AS STATUS,
u.date_created AS DateCreated,
u.NAME AS UserName,
u.password AS Password,
u.email AS Email,
r.token AS Currency,
Cast(u.balance / 100 AS DECIMAL(10, 2)) AS Balance,
Count(o.user_id) AS TotalShippedOrders
FROM [db].[user] u
INNER JOIN [db].[region] r
ON r.currency_id = u.balance_currency
LEFT JOIN [db].[order] o
ON o.user_id = u.id
AND o.status = 'shipped'
GROUP BY u.id,
u.date_created,
u.NAME,
u.password,
u.email,
r.token,
u.balance
ORDER BY TotalShippedOrders DESC;
我试图LEFT JOIN地址表,但它通过TotalShippedOrders计数。
SELECT ( CASE
WHEN u.password IS NULL THEN 'GUEST'
ELSE 'CUSTOMER'
END ) AS STATUS,
u.date_created AS DateCreated,
u.NAME AS UserName,
u.password AS Password,
u.email AS Email,
r.token AS Currency,
Cast(u.balance / 100 AS DECIMAL(10, 2)) AS Balance,
Count(o.user_id) AS TotalShippedOrders,
a.*
FROM [db].[user] u
INNER JOIN [db].[region] r
ON r.currency_id = u.balance_currency
LEFT JOIN [db].[order] o
ON o.user_id = u.id
AND o.status = 'shipped'
LEFT JOIN [db].[address] a
ON a.user_id = u.id
GROUP BY u.id,
u.date_created,
u.NAME,
u.password,
u.email,
r.token,
u.balance
ORDER BY TotalShippedOrders DESC;
有人能指出我如何制定我的查询的这一部分吗?谢谢!
编辑:我在计数中添加了DISTINCT,这似乎解决了问题,但我还没想到它还在返回所有用户/地址组合。这个简单的查询返回的行数多于上面的行:
select * from [db].[user] u
LEFT JOIN [db].[address] a ON a.user_id = u.id
order by u.id
我希望每行都能看到用户信息和一个地址。如果用户有多个地址,则会有许多行具有相同的用户信息但地址不同。有些用户没有地址,这就是我进行LEFT JOIN的原因。
有人能指出我查询逻辑出错的地方吗?谢谢!
答案 0 :(得分:1)
您的问题表明每个用户有多个地址。也许你只想要一个地址,比如最近的地址。如果是这样,这样的事情应该有效:
SELECT . . .
FROM [db].[user] u INNER JOIN
[db].[region] r
ON r.currency_id = u.balance_currency LEFT JOIN
[db].[order] o
ON o.user_id = u.id AND o.status = 'shipped' LEFT JOIN
(SELECT a.*,
ROW_NUMBER() OVER (PARTITION BY a.user_id ORDER BY a.id DESC) as seqnum
FROM [db].[address] a
) a
ON a.user_id = u.id AND a.seqnum = 1
. . .
它使用地址表中id最大的地址。
编辑:
如果您需要所有地址,则需要在聚合后进行连接:
with t as (
<your query here with "u.id as user_id" in the select
)
select t.*, a.*
from t left join
addresses a
on t.user_id = a.user_id;