MySQL:从多个表中选择数据

时间:2014-11-03 15:35:44

标签: mysql

我有3个订单表

Orders1

OrderNumber, TransactionID, TrackingNumber

Orders2

OrderNumber, TransactionID, TrackingNumber

Orders3

OrderNumber, TransactionID, TrackingNumber

我显示了未完成的订单总数,因此我需要从TrackingNumber = ''

的表格中进行选择

3 个答案:

答案 0 :(得分:0)

您需要使用UNION

SELECT * FROM orders1 WHERE TrackingNumber = ''
UNION
SELECT * FROM orders2 WHERE TrackingNumber = ''
UNION
SELECT * FROM orders3 WHERE TrackingNumber = ''

答案 1 :(得分:0)

这是一种使用子查询的方法。

SELECT
  (SELECT COUNT(*) FROM Orders1 WHERE TrackingNumber='')
  + (SELECT COUNT(*) FROM Orders2 WHERE TrackingNumber='')
  + (SELECT COUNT(*) FROM Orders3 WHERE TrackingNumber='')
AS `total`
FROM DUAL;

告诉我它是否按预期工作:)

值得一提的是,您应该将TrackingNumber字段编入索引。

答案 2 :(得分:0)

试试这个:

select 
    sum(a.subtotal )
from
    (select count(*) as subtotal from Orders1 where TrackingNumber=''
    union all
    select count(*) as subtotal from Orders2 where TrackingNumber=''
    union all
    select count(*) as subtotal from Orders3 where TrackingNumber=''
   ) a