【问题标题】:how to join three tables with one output如何用一个输出连接三个表
【发布时间】:2021-09-17 18:17:08
【问题描述】:

我有下面的 sql 语句,我希望将 3 个表连接起来并有 1 个输出。问题是,没有错误,但没有显示我想要的输出。

$sql = "select distinct(sales_table.sales_id), trades_table.t_symbol, round(sum(trades_table.t_volume),2) as totalvol from trades_table inner join accounts_table on trades_table.t_login = accounts_table.a_login inner join sales_table where accounts_table.a_comment = sales_table.sales_id  group by trades_table.t_symbol";

我的表格文件

sales_table

sales_id sales_name
john john doe
jake jake dog

交易表

t_deal t_login t_symbol t_volume
1111 4000 fb 2.00
1112 4001 tesla 1.00
1113 4001 tesla 1.00
1114 4002 apple 3.00

accounts_table

a_login a_name a_comment
4000 test1 john
4001 test2 john
4002 test2 jake

我想要的输出是

约翰

trades_table.t_symbol round(sum(trades_table.t_volume),2)
fb 2.00
tesla 2.00

杰克

trades_table.t_symbol round(sum(trades_table.t_volume),2)
apple 3.00

我希望有人可以帮助我如何正确使用 3 个表的内部联接。

非常感谢

【问题讨论】:

  • 我不知道发生了什么,但是当我创建这个帖子时,表格格式可以正常工作并且它显示在预览中,但是当我发布时,你看到的事情就会发生
  • 你的意思是加入三个数据库还是三个?也请输出你目前得到的。
  • 3 个表有 1 个输出。上面 sql 代码的输出是 sales_id: john t_symbol: fb totalvol: 2.00 sales_id: john t_symbol: tesla totalvol: 2.00 sales_id: jake t_symbol: apple totalvol: 3.00
  • 请分享更多细节。您如何运行该查询?您尝试过什么来解决问题?

标签: mysql sql json


【解决方案1】:

看来你需要简单

SELECT t1.a_login, t3.t_symbol, SUM(t3.t_volume) total_volume
FROM accounts_table t1
JOIN sales_table t2 ON t1.a_comment = t2.sales_id
JOIN trades_table t3 ON t1.a_login = t3.t_login
GROUP BY t1.a_login, t3.t_symbol

如果您只需要在数据中指定t1.a_login,则根据WHERE添加。

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2014-01-01
    • 2017-08-24
    • 2016-09-27
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多