如何使用单个查询获取存储在不同变量中的多个表行的计数?

时间:2017-11-08 15:49:53

标签: mysql sql database google-bigquery

我有4个不同的表,我想获取每个表的计数行,并获得4个不同变量的计数(*)。

我使用的查询是:

 SELECT count(*) as count1 FROM `table1` 
 UNION ALL 
 SELECT count(*) as count2 FROM `table2`
 UNION ALL 
 SELECT count(*) as count3 FROM `table3`
 UNION ALL
 SELECT count(*) as count4 FROM `table4`

查询给出了每行的计数,但所有值都存储在相同的变量名称中。

 [
  {
    "count1": 16171
  }, 
  {
    "count1": 5928
  }, 
  {
    "count1": 33318
  }, 
  {
    "count1": 5877
  }
 ]

有没有办法让输出为;

 [
  {
    "count1": 16171
  }, 
  {
    "count2": 5928
  }, 
  {
    "count3": 33318
  }, 
  {
    "count4": 5877
  }
 ]

提前致谢。

2 个答案:

答案 0 :(得分:1)

UNION ALL联合行。听起来您只想列出选择列表中的每个计数。试试这个:

SELECT
  (SELECT COUNT(*) FROM `table1`) AS count1,
  (SELECT COUNT(*) FROM `table2`) AS count2,
  (SELECT COUNT(*) FROM `table3`) AS count3,
  (SELECT COUNT(*) FROM `table4`) AS count4
;

答案 1 :(得分:0)

以下是BigQuery Standard SQL

  
#standardSQL
SELECT 
  table_id,
  row_count
FROM `yourProject.yourDataset.__TABLES__`   
WHERE table_id in ('table1', 'table2', 'table3', 'table4')

这种方法允许你获得(免费!!),而不仅仅是行数 - 见下面的例子

#standardSQL
SELECT table_id,
  DATE(TIMESTAMP_MILLIS(creation_time)) AS creation_date,
  DATE(TIMESTAMP_MILLIS(last_modified_time)) AS last_modified_date,
  row_count,
  size_bytes,
  CASE
    WHEN type = 1 THEN 'table'
    WHEN type = 2 THEN 'view'
    WHEN type = 3 THEN 'external'
    ELSE '?'
  END AS type,
  TIMESTAMP_MILLIS(creation_time) AS creation_time,
  TIMESTAMP_MILLIS(last_modified_time) AS last_modified_time,
  dataset_id,
  project_id
FROM `bigquery-public-data.baseball.__TABLES__`