1

使用 mysql 我试图从where tid='any tid' 我尝试过的所有表中计算 ID,它给出了"Column 'tid' in where clause is ambiguous". 我需要使用 join 吗?

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

4 回答 4

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

说明:Doingfrom table1, table2, table3将在所有这些表之间进行连接。由于没有连接标准,它会执行所有可能的连接,例如 table1 中的一行、table2 中的一行和 table3 中的一行的每种可能组合都会在这种查询中产生结果。

于 2013-02-20T05:54:28.193 回答
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

例如,如果您只想在 1 行中回答,则可以使用 5,10 和 15,您可以使用@peterm 的回答

于 2013-02-20T05:56:41.540 回答
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

于 2013-02-20T05:58:31.730 回答
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
于 2013-02-20T06:01:12.280 回答