在MySQL中将两个查询连接在一起

时间:2018-11-30 22:21:27

标签: mysql sql

我有两个独立的查询: Employee Manager ,它们可以很好地工作并且可以,但是我希望合并所有 COLUMNS 来自两个查询。这可能吗?我显然不希望得到完整的答案,但是希望对实现此目的的可能方法有所了解。

员工查询:

SELECT
  shopTableRef.shopname AS "Shop Name:",
  perTableRef.personname AS "Employee Name:",
  COUNT(inStoreTableRef.payid) AS "Total Sales:",
  SUM(payTableRef.amount) AS "Sales Value (£):"
FROM
  fss_Person perTableRef
JOIN
  fss_Employee empTableRef ON perTableRef.personid = empTableRef.empid
JOIN
  fss_InstorePayment inStoreTableRef ON empTableRef.empid = inStoreTableRef.empid
JOIN
  fss_Payment payTableRef ON payTableRef.payid = inStoreTableRef.payid
JOIN
  fss_Shop shopTableRef ON payTableRef.shopid = shopTableRef.shopid
WHERE
  empTableRef.roleid = 2
GROUP BY
  perTableRef.personname
ORDER BY
  COUNT(inStoreTableRef.payid) DESC

经理查询:

SELECT
  perTableRef.personname AS "Manager's Name:"
FROM
  fss_Person perTableRef
JOIN
  fss_Employee empTableRef ON perTableRef.personid = empTableRef.empid
JOIN
  fss_Manager manTableRef ON empTableRef.empid = manTableRef.empid
WHERE
  empTableRef.roleid = 1
GROUP BY
  perTableRef.personname

我尝试了以下操作:UNION,UNION ALL,INNER JOIN,JOIN和嵌套查询,但似乎没有任何作用。

1 个答案:

答案 0 :(得分:1)

UNION或UNION ALL应该进行一些调整。

  1. 每个查询必须返回相同数量/类型的列,因此对于缺少的列,请在NULL AS "Shop Name:"等中填写您的Manager查询。
  2. 组合查询只允许使用一个ORDER BY,因此请确保该查询排在最后,并以其别名"Total Sales:"引用订购列