我有这个有效的查询
SELECT t1.id as stockid, t1.description as stockdescription, t2.inkoop as price , COUNT(t2.inkoop) as cnt,
(t2.inkoop * COUNT(t2.inkoop)) as totalamount
FROM database1.table_products t1
LEFT JOIN database1.table_stock t2 ON t1.id = t2.stock_id
WHERE 1
GROUP BY t2.inkoop
ORDER BY t1.id ASC
1个数据库,2个表: t1是带有ID和描述的产品'描述'数据库 t2是股票,它有很多产品的价格(购买)和stock_id
引用Output:
id stockdescription price cnt totalamount
1 Product1 1067 15 16005
1 Product1 1290 103 132870
2 Product2 2750 70 192500
3 Product3 500 0 0
但是现在我有第二个数据库(database2)和第二个库存表(stock2)(与database1.table_stock结构完全相同)
如何更改我的查询,以便我还可以添加'cnt2'并将总数更改为我的结果?
Like this:
id stockdescription price cnt cnt2 totalcnt totalamount
1 Product1 1067 15 0 15 16005
1 Product1 1290 103 0 103 132870
2 Product2 2750 70 5 75 206250
3 Product3 500 0 4 4 2000
答案 0 :(得分:1)
您可以加入多个表,但是您将获得两个库存表的完全连接,这意味着您在GROUP BY
之后得到错误的计数。您可以通过嵌套查询来避免这种情况,例如:沿着这些方向:
SELECT sub.*, COUNT(stock2.inkoop) AS cnt2
FROM ( <paste your query here> ) AS sub
LEFT JOIN database2.stock2 AS stock2 ON sub.stockid = stock2.stock_id
GROUP BY sub.stockid
ORDER BY sub.stockid ASC
现在您有两个左连接,每个连接都有自己的GROUP BY
。因此,每个左连接只能看到一个左手表因子,并且您不会因同时连接太多表而导致重复。