在一个查询中计算来自不同表的结果

时间:2013-03-01 07:35:21

标签: mysql

我有ordersorder_attachmentsorder_preship_checkorder_preship_check_attachmentorder_logorder_log_attachments

这些列中唯一常见的是order_id。现在在查询中我只使用以下查询检查那些类型1和类型2的order_attachments

SELECT
    COUNT(file_id) AS totalFiles
FROM
    orders_files
WHERE
    order_id = '88125'
AND attachment_type IN ('1', '2')

因此,如果它返回,我会显示带有该订单的ATTACHMENTS图标。现在我需要将preship附件和日志附件组合在一起。没有额外的检查,两者的个别查询如下

SELECT
    COUNT(file_id) AS totalFiles
FROM
    orders_preship_check_attachment
WHERE
    order_id = '88125'

SELECT
    COUNT(id) AS totalFiles
FROM
    orders_log_attachment
WHERE
    order_id = '88125'

我需要在一个查询中组合这3个查询。因此,如果每个表有1条记录,我只需要计数3,即使3也不重要。意味着如果这些记录中的任何一个有附件我需要显示图标,TRUE或FALSE。我希望它能说得更清楚

2 个答案:

答案 0 :(得分:1)

使用UNION或UNION ALL,但必须具有相同的类型和列数。

示例代码:

    SELECT 'Customer' AS type, id, name FROM customer
    UNION ALL
    SELECT 'Supplier', id, name FROM supplier

如果您的查询包含不同数量的列,请尝试使用连接。

答案 1 :(得分:1)

试试这个

SELECT SUM(totalFiles) AS totalFiles
  FROM (
    SELECT COUNT(file_id) AS totalFiles
      FROM orders_files
     WHERE order_id = '88125' AND
           attachment_type IN ('1', '2')
     UNION ALL
    SELECT COUNT(file_id) AS totalFiles
      FROM orders_preship_check_attachment
     WHERE order_id = '88125'
     UNION ALL
    SELECT COUNT(id) AS totalFiles
      FROM orders_log_attachment
     WHERE order_id = '88125'
    ) t

SELECT COUNT(file_id) AS totalFiles
  FROM (
    SELECT file_id
      FROM orders_files
     WHERE order_id = '88125' AND
           attachment_type IN ('1', '2')
     UNION ALL
    SELECT file_id
      FROM orders_preship_check_attachment
     WHERE order_id = '88125'
     UNION ALL
    SELECT id
      FROM orders_log_attachment
     WHERE order_id = '88125'
    ) t