我是数据库领域的新手。我目前正在使用Murach的Mysql学习mysql。我在书中遇到了以下问题,但我无法弄清楚解决它的正确查询。
写一个SELECT语句 加入 客户,订单,Order_Items和 产品表。该语句应返回以下列: 姓, 名字, order_date,product_na 我,item_price,discount_amount, 和 数量 。 为表使用别名。 对最终结果进行排序 持续 _名称, 订购 _date,和 产品名称
到目前为止,我有这个问题:
select last_name , first_name , order_date , product_name , tem_price,
discount_amount, quantity
from customers , orders , order_items product
order by last_name , order_date , product_name
答案 0 :(得分:1)
您可以对这4个表Customers
,Orders
,Order_items
,Products
使用内部联接,但请确保这3个表中的列之间存在匹配。
Select A.last_name,A.first_name,B.order_date,B.product_name,C.item_price,C.discount_amount,D.quantity
from TB_Customers A inner join TB_Orders B on A.CustomerID = B.CustomerID
inner join TB_Order_Items C on B.CustomerID = C.CustomerID on
inner join TB_Products D on C.CustomerID = D.CustomerID Where D.CustomerID ='TEST111'
答案 1 :(得分:1)
使用ANSI标准连接语法:
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c
INNER JOIN Orders AS o ON c.order_id = o.order_id
INNER JOIN Order_Items AS i ON o.order_id = i.order_id
INNER JOIN Products AS p ON i.product_id = p.product_id
ORDER BY c.last _name, o.order _date, p.product_name
答案 2 :(得分:0)
好吧,我们将分析查询。由于你没有指定数据库结构,我将做一个aproaching。
“连接Customers,Orders,Order_Items和Products表的SELECT语句。”
这是表格,这是在 FROM 子句中。您必须使用 WHERE 子句加入它们。
SELECT *
FROM Customers, Orders, Order_Items, Products
WHERE Customers.order_id = Orders.order_id
AND Order_Items.order_id = Orders.order_id
AND Products.product_id = Order_Items.product_id
“此语句应返回以下列:last_name,first_name,order_date,product_na me,item_price,discount_amount和quantity ”
这部分是指 SELECT 子句。
SELECT last_name, first_name, order_date, product_name,
item_price, discount_amount, quantity
FROM Customers, Orders, Order_Items, Products
WHERE Customers.order_id = Orders.order_id
AND Order_Items.order_id = Orders.order_id
AND Products.product_id = Order_Items.product_id
“使用表格的别名”
这部分涉及整个查询,意味着必须重命名表(虚拟地,仅形成此查询),并且在每个引用中都必须使用新名称。
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c, Orders AS o, Order_Items AS i, Products AS p
WHERE c.order_id = o.order_id
AND i.order_id = o.order_id
AND p.product_id = i.product_id
“按最后_name,order _date和product_name对最终结果进行排序。”
这部分是指 ORDER BY 子句。你必须记住别名
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c, Orders AS o, Order_Items AS i, Products AS p
WHERE c.order_id = o.order_id
AND i.order_id = o.order_id
AND p.product_id = i.product_id
ORDER BY c.last _name, o.order _date, p.product_name