只是了解UNION查询 - 节省时间 - 但是在分组方面遇到了麻烦。
我有以下声明:
(SELECT `shops`.shpUserAdded AS userName, count(`shops`.shpID) AS shpCount, "" AS prdCount FROM `shops` GROUP BY shpUserAdded ASC)
UNION
(SELECT `products`.prdUserAdded AS userName, "" AS shpCount, count(`products`.prdID) AS prdCount FROM `products` GROUP BY prdUserAdded ASC)
但是这给了我第一个查询的结果,然后是第二个查询的结果,没有组合用户名:
userName|merCount|prdCount
| 8|
Jane | 1|
Derek | 1|
James | 22|
| | 3
Jane | | 4
Derek | | 5
James | | 21
我尝试过(但显然得到了#1248 - Every derived table must have its own alias
):
SELECT userName, shpCount, prdCount FROM
((SELECT `shops`.shpUserAdded AS userName, count(`shops`.shpID) AS shpCount, "" AS prdCount FROM `shops` GROUP BY shpUserAdded ASC)
UNION
(SELECT `products`.prdUserAdded AS userName, "" AS shpCount, count(`products`.prdID) AS prdCount FROM `products` GROUP BY prdUserAdded ASC))
GROUP BY userName ASC
我似乎无法在不擦除shpCount或prdCount列中的数据的情况下找出派生表的命名 - 任何建议?我可能会感到愚蠢,但是在那里!
解决了(真的这次)! :)
SELECT Users.userName, Products.prdCount, Shops.shpCount FROM
(
(
(SELECT `Shops`.shpAddU AS userName FROM `Shops` GROUP BY shpAddU ASC)
UNION
(SELECT `Products`.prdAddU AS userName FROM `Products` GROUP BY prdAddU ASC)
) AS Users
)
LEFT JOIN
(SELECT prdAddU AS userName, count(*) AS prdCount FROM `Products` GROUP BY prdAddU) as Products ON Users.userName = Products.userName
LEFT JOIN
(SELECT shpAddU AS userName, count(*) AS shpCount FROM `Shops` GROUP BY shpAddU) as Shops ON Users.userName = Shops.userName
答案 0 :(得分:4)
并非所有东西都是联盟 - 在这种情况下,它是子查询的连接:
SELECT shpUserAdded AS userName, merCount, prdCount
FROM (SELECT shpUserAdded, count(*) AS shpCount FROM shops GROUP BY shpUserAdded ASC) AS s
JOIN (SELECT prdUserAdded, count(*) AS prdCount FROM products GROUP BY prdUserAdded ASC) AS p
ON (shpUserAdded = prdUserAdded);