来自Mysql

时间:2015-08-11 16:45:52

标签: mysql union

我有以下查询 -

(SELECT entry_by_id, description, 
issue_date AS issue_date,
bill_type_id AS account_type, 
amount 
FROM ac_bills 
WHERE issue_date BETWEEN '2015-08-01' and '2015-08-31')  
UNION  
(select officer_id AS entry_by_id, description,
tr_date AS issue_date,
account_type_id AS account_type, 
amount 
FROM ac_transactions 
WHERE ac_transactions.tr_date BETWEEN '2015-08-01' AND '2015-08-31' 
AND ac_transactions.account_type_id 
IN (SELECT id FROM account_types WHERE type_of_nature=2))  
ORDER BY issue_date DESC, account_type ASC

如你所见 -

1. account_types表(在子查询中)有一个type_of_nature列,它告诉我一个项目的交易类型(1 =收入和2 =费用)

2. 我试图从两个表中扣除所有费用 - ac_bills和ac_transactions。 ac_bills只保存费用,而ac_transactions可以保存任何类型的交易(收入/支出),我们通过account_types表引用知道交易的类型。

问题 - 从理论上讲,查询从ac_transactions表中提取所有类型的事务,应该只提取费用。有趣的是 - 当我在没有union部分的情况下单独运行ac_transactions上的select查询时,它成功地只提取费用。 我把头发拉出来!谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

你可以运行这个......不确定它是否正确,但它至少看起来更清洁

(
 SELECT entry_by_id
      , description
      , issue_date 
      , bill_type_id account_type
      , amount 
   FROM ac_bills 
  where issue_date between '2015-08-01' and '2015-08-31'
)
  union  
(
 select officer_id entry_by_id
      , description
      ,tr_date 
      , account_type_id 
      , amount 
   from ac_transactions 
   join account_types 
     ON account_types.id = ac_transactions.account_type_id 
  where ac_transactions.tr_date between '2015-08-01' and '2015-08-31' 
    and account_types.type_of_nature = 2
)
  ORDER 
     BY issue_date DESC
      , account_type ASC;