mysql查询来计算id

时间:2013-02-20 05:52:21

标签: mysql

使用mysql我试图计算所有表where tid='any tid'中的ID 我试过了以下查询,它给出了"Column 'tid' in where clause is ambiguous"。 我需要使用加入吗?

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

4 个答案:

答案 0 :(得分:0)

由于您要从每个表中收集行而不是加入它们,因此您需要执行UNION,如:

 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中的一行的每个可能组合都将在该类查询中产生结果。

答案 1 :(得分:0)

使用UNIONS

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
例如,如果您只想在1行中回答,可以使用@ peterm的答案

5,10和15

答案 2 :(得分: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

答案 3 :(得分: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