mySQL,我如何一起加入2个查询?

时间:2017-04-09 17:10:15

标签: mysql sql join phpmyadmin

我只有2个查询:

查询1:

SELECT orderID, paid, orderPrice, orderDate, payDate, Orders.customerID, Customers.cusName, Customers.cusEmail, Customers.totalOrderVolume, sum(orderPrice)
FROM Orders
INNER JOIN Customers
ON Orders.customerID=Customers.customerID
WHERE paid = 1
GROUP BY customerID

QUERY2:

SELECT count(*) "numberTest"
FROM Orders
GROUP BY customerID

我在运行时将它们一起加入到1个输出表中,因此您可以看到第一个查询有10列而另外1列,如何将第二个查询中的1列添加到第一个查询中输出是一个表,其中1列添加到结尾,因此输出表在运行时有11列。

在此先感谢,我花了好几个小时试图解决这个问题,我是一名SQL初学者,我无法弄明白。

提前致谢。

3 个答案:

答案 0 :(得分:0)

SELECT A.orderID,A.paid,A.orderPrice,A.orderDate,A.payDate,A.customerID,A.cusName,A.cusEmail,A.totalOrderVolume,A.sum,B.numberTest 从 (SELECT orderID,paid,orderPrice,orderDate,payDate,Orders.customerID as customerID,Customers.cusName,Customers.cusEmail,Customers.totalOrderVolume,sum(orderPrice)as sum FROM Orders INNER JOIN Customers ON Orders.customerID = Customers.customerID WHERE paid = 1 GROUP BY customerID)为A 内部联接 (SELECT Orders.customerID as customerID,count(*)as numberTest FROM Orders GROUP BY customerID)as B ON A.customerID = B.customerID

**我认为customerID对于这两个表都是通用的。

答案 1 :(得分:0)

SELECT A.orderID,A.paid,A.orderPrice,A.orderDate,A.payDate,A.customerID,A.cusName,A.cusEmail,A.totalOrderVolume,A.sum,B.numberTest FROM(SELECT orderID,paid,orderPrice,orderDate,payDate,Orders.customerID as customerID,Customers.cusName,Customers.cusEmail,Customers.totalOrderVolume,sum(orderPrice)as sum FROM Orders INNER JOIN Customers ON Orders.customerID = Customers.customerID WHERE paid = 1 GROUP BY customerID)作为INNER JOIN(SELECT Orders.customerID as customerID,count(*)as numberTest FROM Orders GROUP BY customerID)as B ON A.customerID = B.customerID

答案 2 :(得分:-1)

从您的问题中不清楚这两个查询的目标是什么,以及它们是如何相关的,但这可以按照您在问题中提出的方式进行。

SELECT 
    orderID,
    paid,
    orderPrice,
    orderDate,
    payDate,
    Orders.customerID,
    Customers.cusName,
    Customers.cusEmail,
    Customers.totalOrderVolume,
    sum(orderPrice),
    count(*) as `numberTest`
FROM Orders
INNER JOIN Customers
ON Orders.customerID=Customers.customerID
WHERE paid = 1
GROUP BY customerID