我有5张桌子:
CREATE TABLE Client_master(
Client_no int(5),
Client_name varchar(10),
c_address varchar(10),
Bdate date,
PRIMARY KEY(Client_no)
);
CREATE TABLE Product_master(
product_no int(5),
Description varchar(20),
saleprice int(5),
costprice int(5),
PRIMARY KEY(product_no)
);
CREATE TABLE Sales_master(
Salesmno int(5),
Sname varchar(10),
s_address varchar(5),
salary float(5),
Remarks varchar(10),
PRIMARY KEY(Salesmno)
);
CREATE TABLE Sales_order(
order_no int(5),
Client_no int(5),
Odate date,
Delv_add varchar(20),
Salesmno int(5),
PRIMARY KEY(order_no),
FOREIGN KEY(Client_no) REFERENCES Client_master(Client_no),
FOREIGN KEY(Salesmno) REFERENCES Sales_master(Salesmno)
);
CREATE TABLE Sales_order_detail(
order_no int(5),
product_no int(5),
qty_order int(5),
product_rate int(5),
qty_dispatch int(5),
FOREIGN KEY(order_no) REFERENCES Sales_order(order_no),
FOREIGN KEY(product_no) REFERENCES Product_master(product_no)
);
我必须确定购买超过250美元的客户的名称。 我试过这个:
SELECT cm.Client_name, sum(pm.saleprice * sod.product_no)
FROM Sales_order_detail sod
LEFT JOIN Product_master pm ON sod.product_no = pm.product_no
LEFT JOIN Sales_order so ON sod.order_no = so.order_no
LEFT JOIN Client_master cm ON so.Client_no = cm.Client_no
GROUP BY cm.Client_no WHERE sum(pm.saleprice * sod.product_no) > 250;
但它会出现这样的错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 'WHERE sum(pm.saleprice * sod.product_no)>附近第6行250'
答案 0 :(得分:1)
from
子句应该在having
子句之后,因此您需要在此使用where
子句而不是SELECT cm.Client_name, sum(pm.saleprice * sod.product_no)
FROM Sales_order_detail sod
LEFT JOIN Product_master pm ON sod.product_no = pm.product_no
LEFT JOIN Sales_order so ON sod.order_no = so.order_no
LEFT JOIN Client_master cm ON so.Client_no = cm.Client_no
GROUP BY cm.Client_no
having sum(pm.saleprice * sod.product_no) > 250;
a = enumerate('abcdef')
b = enumerate('ghi')
for i, j in zip(a, b):
print(i, j)
if i[0] == 0:
next(itertools.islice(zip(a, b), 1, 1), None)
答案 1 :(得分:1)
您的语法错误是由where
引起的。但是你不需要left join
。您可以将查询编写为:
SELECT cm.Client_name, sum(pm.saleprice * sod.product_no) as total
FROM Sales_order_detail sod JOIN
Product_master pm
ON sod.product_no = pm.product_no JOIN
Sales_order so
ON sod.order_no = so.order_no JOIN
Client_master cm
ON so.Client_no = cm.Client_no
GROUP BY cm.Client_no
HAVING total > 250;
请注意,您还可以使用列别名并在HAVING
子句中使用它。