查询以计算多个表上的字段上的不同值

时间:2015-03-24 23:03:33

标签: mysql sql database select

SQL查询:

Select count(distinct signature)
from (Select table_name
      from information_schema.tables
      where table_schema="Log" and table_name like "%ERROR_%")
AS mytable;

预期输出:不同的"签名"来自所有表格。

实际输出:未知列'签名'在'字段列表';

注意:我的所有表都有签名和字段名称

2 个答案:

答案 0 :(得分:0)

好吧,你的子查询就像这样开始:

Select table_name from information_schema.tables

因此您可以使用的单个列是“table_name”。

因此,如果您尝试从该子查询中选择签名,它会告诉您没有这样的列。

您可能想要做这样的事情(伪代码):

query(
    Select table_name 
    from information_schema.tables 
    where table_schema="Log" and table_name like "%ERROR_%"
)
$sql = '';
$sep = '';
while ($row = fetch_assoc()) {
    $sql .= $sep."SELECT signature FROM $row[table_name] ";
    $sep = 'UNION ALL ';
}
$sql = "SELECT COUNT(DISTINCT signature) as c FROM ($sql)";
query($sql);
$row = fetch_assoc()
echo "There are $row[c] distinct signatures.<br />\n";

答案 1 :(得分:0)

看起来你在mysql端尝试动态查询。请检查一下......

-- Step1. prepare your select query here
set @sqlQuery := 
(select
 GROUP_CONCAT(
  concat(' SELECT \'',table_name,'\' as col1,  COUNT(*) as countItem FROM ', table_name)
  SEPARATOR ' UNION ALL '
)  from information_schema.tables as t
where t.table_schema="Log" and t.table_name like "%ERROR_%");

-- Step2. execute the dynamic query
prepare stmt from @sqlQuery;
execute stmt;
drop prepare stmt;
相关问题