我一直在尝试将多个表组合成一个我可以使用的 json 对象。希望我能解释我想做什么。
我有 3 个表:
交易表
id、客户、地址、城市、州、 zip
代理表
身份证、名字、姓氏
agent_transaction
id, agent_id, transaction_id
下面是它们是如何联系在一起的:
transactions.id = agent_transaction.transaction_id
agent_transaction.agent_id = agents.id
单个事务可以有多个代理(插入到 agent_transaction 中)。我希望从 SQL 查询中获取以下内容:
获取每个交易的列表...以及分配给该交易的所有代理...并收集代理信息(名字、姓氏等)。
所以,它看起来像这样:
所有交易:[ {
id: 20
client: Joe Smith
address: 123 Fake Dr
city: Phoenix
state: AZ
zip: 85248
agents:{
agent_id: 39
first_name: John
last_name: Doe
},{
agent_id: 40
first_name: Kelly
last_name: Parker
},{
agent_id: 41
first_name: Carl
last_name: Williams
}
},{
id: 21
client: Mary Swamson
address: 240 Someplace Dr
city: Seattle
state: WA
zip: 98233
agents:{
agent_id: 12
first_name: Billy
last_name: Banks
},{
agent_id: 98
first_name: Sharon
last_name: Gandt
}
} ]
我已经尝试使用一些内部联接,但我得到了每个返回的代理的重复事务行。我现在正在研究 STRING_AGG 函数,希望它能返回我正在寻找的内容。
谢谢
最佳答案
我相信我已经解决了,使用 STRING_AGG:
SELECT t.id,t.address, STRING_AGG(a.first_name, ';') AS agents FROM trans AS t
INNER JOIN agent_trans AS at ON (t.id = at.transaction_id)
INNER JOIN agents AS a ON (a.id = at.user_id)
GROUP BY t.id,t.address
ORDER BY t.id;
我显然需要包括我所有的其他领域,但这似乎是我正在寻找的。p>
关于SQL 查询 : joining 3 tables with multiple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427892/