mysql - Sql 连接三表

标签 mysql sql sql-server database

这是我的表格..我想要这个输出:

pid | pname | custname | quantity | total base price | sale price | profit

架构:

create table customers
(
    cid int,
    cname varchar(1000),
    cg varchar(1000)
)

create table prod
(
    pid int,
    pname varchar(1000),
    baseprice int,
    saleprice int
)

create table orders
(
    oid int,
    custid int,
    pid int,
    quantity int,
    odate date
)

如何为此编写查询?

最佳答案

--pid | pname | custname | quantity | total base price | sale price | profit
select o.pid, p.pname, c.cname AS custname, SUM(o.quantity) AS quantity, 
SUM(p.baseprice) AS 'total base price', SUM(p.saleprice) AS 'sale price', 
SUM(p.baseprice) - SUM(p.saleprice) AS profit -- change this math to what you need
from orders o join prod p
on o.pid = p.pid
join customers c
on o.custid = c.cid
group by o.pid, p.pname, c.cname

关于mysql - Sql 连接三表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327753/

相关文章:

php - MySQL先插入后删除

php - 对超过 100 万行的表运行查询

用于导出的 MySQL 批处理文件调用刷新表

mysql - 意想不到的角色。 ( "\"附近

sql - 从一行中具有相同 id 的一张表中选择最小值和最大值

sql-server - 哪个插入速度更快,XML 字段还是 Varchar(max) 字段?

如果满足条件,SQL 执行内连接

mysql - 我可以在 MySQL 中使用任一命令吗?索引和外键

sql-server - 在 SQL 中返回列中所有可能的值组合

SQL 服务器 : Add a column with calculated Field