2013-02-20 68 views
1

使用mysql我想從所有表中統計ID where tid='any tid' 我試過以下查詢,其給出"Column 'tid' in where clause is ambiguous"。 我需要使用連接嗎?mysql查詢計數編號

SELECT count('id') as reccount 
    FROM table1,table2,table3 
    WHERE tid= '101' 
    AND `status` = 1 

我有表結構一樣,

table 1: 
------------------------------ 
id  tid status ........ 
1  101  1 
2  102  1 

table 2: 
------------------------------ 
id  tid status ........ 
1  101  1 
2  102  1 

table 3: 
------------------------------ 
id  tid  status....... 
1  101  1 
2  102  1 

table 4: It contains tid 
-------------------------- 
tid  tname ..... 
101  xyz 
102  abc 
+0

也許你想使用UNION。 – Alex 2013-02-20 05:54:49

+0

你正在使用cartisian產品,它不會取得想要的結果 – 2013-02-20 05:55:15

回答

0

您沒有提供所需的輸出,但如果您的意圖是從所有三個表中只獲得總行數(從原始查詢中推導出來),那麼您可以這樣做:

SELECT COUNT(`id`) AS reccount 
    FROM 
    (SELECT `id` FROM table1 
    WHERE tid= '101' AND `status` = 1 
    UNION ALL 
    SELECT `id` FROM table2 
    WHERE tid= '101' AND `status` = 1 
    UNION ALL 
    SELECT `id` FROM table3 
    WHERE tid= '101' AND `status` = 1) t 

這裏是sqlfiddle

0

既然你從每個表中收集行,不加入他們,你需要做的工會,如:

SELECT count('id') as reccount 
    FROM table1 
    WHERE table1.tid= '101' 
    AND `status` = 1 
UNION 
SELECT count('id') as reccount 
    FROM table2 
    WHERE table2.tid= '101' 
    AND `status` = 1 
UNION 
SELECT count('id') as reccount 
    FROM table3 
    WHERE table3.tid= '101' 
    AND `status` = 1 

說明:執行from table1, table2, table3將在所有這些表之間進行連接。由於沒有加入標準,因此它會進行各種可能的加入,例如來自table1的一行,來自table2的一行和來自table3的一行的每一種可能的組合都會在那種查詢中產生結果。

0

使用工會

SELECT count('id') as reccount , 'Table1' AS table FROM table1 WHERE tid= '101' AND `status` = 1 
UNION 
SELECT count('id') as reccount , 'Table2' AS table FROM table2 WHERE tid= '101' AND `status` = 1 
UNION 
SELECT count('id') as reccount , 'Table3' AS table FROM table3 WHERE tid= '101' AND `status` = 1 

這會給你這樣的

reccount | table 
    5   table1 
    10  table2 
    15  table3 

5,10和15的計數是例如計數,如果你想回答只有1列,您可以使用@ peterm的回答

0

請參見下面的SQL:

SELECT reccount_1 + reccount_2 + reccount_3 as total_count FROM 
(
    SELECT count(`id`) as reccount_1 
    FROM table1 
    WHERE tid= '101' 
    AND `status` = 1 
    UNION 
    SELECT count(`id`) as reccount_2 
    FROM table2 
    WHERE tid= '101' 
    AND `status` = 1 
    UNION 
    SELECT count(`id`) as reccount_3 
    FROM table3 
    WHERE tid= '101' 
    AND `status` = 1 
) 
as temp_table