2012-04-06 112 views
1

我有這2個疑問,我想結合成一個大的查詢別名:MySQL的選擇從多個表

SELECT COUNT(*) AS ac, SUM(Views) AS vc FROM tableA 

SELECT COUNT(*) AS mc FROM tableB 

could'nt關於這個問題找到任何東西,它甚至有可能嗎?

+1

你有什麼共同的列? – Teja 2012-04-06 19:23:27

+0

沒有什麼能阻止你執行這兩個查詢,後者作爲子查詢執行。 – 2012-04-06 19:25:42

+0

@ N.B。你能舉一個例子來說明如何做到這一點嗎? – 2012-04-06 19:27:20

回答

4

您可以使用三個子查詢的方式做:

SELECT 
(SELECT COUNT(*) FROM tableA) AS ac, 
(SELECT SUM(Views) FROM tableA) AS vc, 
(SELECT COUNT(*) FROM tableB) AS mc 

這是不是很優雅的解決方案,但應該做你所需要的。

+0

非常感謝,這是工作! – 2012-04-06 20:54:02

1
SELECT 'tableA' as tablename, COUNT(*) AS count, SUM(Views) AS sum FROM tableA 
UNION 
SELECT 'tableB' as tablename, COUNT(*) AS count, 0 AS sum FROM tableB 
0

您可以創建一個返回SELECT COUNT(*) AS mc FROM tableB的功能和使用表A

CREATE FUNCTION Func1() RETURNS INTEGER 
    BEGIN 
    DECLARE Temp INTEGER; 
    SELECT COUNT(*) INTO Temp FROM tableB; 
    RETURN IFNULL(Temp, 0); 
    END; 

    SELECT COUNT(*) AS ac, SUM(Views) AS vc, Func1() as mc FROM tableA