我想計算一個存在於2個不同表中的值。但應顯示分隔這樣的:Mysql從2個表中計數相同的值作爲2個不同的計數
我當然可以seperately指望它。但我想在一個查詢中得到一個結果。感謝您的幫助
SELECT `X1`, COUNT(`X1`) AS Sales FROM `table1` GROUP BY `X1`
SELECT `X1`, COUNT(`X1`) AS Purchases FROM `table2` GROUP BY `X1`
我想計算一個存在於2個不同表中的值。但應顯示分隔這樣的:Mysql從2個表中計數相同的值作爲2個不同的計數
我當然可以seperately指望它。但我想在一個查詢中得到一個結果。感謝您的幫助
SELECT `X1`, COUNT(`X1`) AS Sales FROM `table1` GROUP BY `X1`
SELECT `X1`, COUNT(`X1`) AS Purchases FROM `table2` GROUP BY `X1`
這是一種痛苦,因爲每個表中的x1
值的集合可能不一樣。
下面是使用union all
和group by
一種方法:
select x1, sum(sales) as sales, sum(purchases) as purchases
from ((select x1, count(*) as sales, 0 as purchases
from table1
group by x1
) union all
(select x2, 0, count(*)
from table2
group by x1
)
) t12
group by x1;
使用子查詢從表中的一個獲得計數,然後再加入與其他表。
SELECT t1.x1, COUNT(*) AS sales, t2.purchases
FROM table1 AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
FROM table2
GROUP BY x1) AS t2
ON t1.x1 = t2.x1
GROUP BY t1.x1
在兩個子查詢中進行分組可能確實更高效。
SELECT t1.x1, t1.sales, t2.purchases
FROM (SELECT x1, COUNT(*) AS sales
FROM table1
GROUP BY x1) AS t1
JOIN (SELECT x1, COUNT(*) AS purchases
FROM table2
GROUP BY x1) AS t2
ON t1.x1 = t2.x1
但是,如果有任何x1
值不在兩個表中,這兩個查詢將離開他們。理想的解決方案是FULL OUTER JOIN
,但MySQL不具備此操作。有關解決方法,請參見Full Outer Join in MySQL。 Gordon Linoff的答案沒有這個問題。或者,如果您有另一個列出所有x1
值的表,則可以將其用作主表,並使用LEFT JOIN
以上兩個子查詢。
工作。非常感謝 – Mare00