如何连接两个表之间的条件

时间:2017-10-09 10:29:41

标签: mysql

我有两个表名收入和费用。我想加入两个表并获取两个日期范围值之间的数据。

Income                  
=============         
id income_name      income_price income_date              
1  admission              30    2017-10-10
2  hostel                 40    2017-10-9
3  bus                    50    2017-10-7

expenses                  
=============
id expenses_name      expenses_price expenses_date              
1  furniture                30    2017-10-9
2  teacher                  40    2017-10-8
3  bus                      60    2017-10-7

我想从2017-10-6到2017-10-10之间的两个表中检索数据。请帮助我。 结果表
 =============

id income_name      income_price      expense_name       expenses_price             
    1  admission         30               furniture       30
    2  hostel           40                 teacher        40
    3  bus                50               bus            60 

2 个答案:

答案 0 :(得分:2)

您可以使用union运算符合并两个或多个查询的结果集

Select * from income where (date between 'your_start_date' and 'your_end_date')
UNION
Select * from expenses where (date between 'your_start_date' and 'your_end_date')

默认情况下,UNION运算符仅选择不同的值。要允许重复值,请使用UNION ALL

答案 1 :(得分:0)

使用union all加入获取数据的2个表的结果集。以下是查询。

select *
from Income
where date between '2017-10-6' and '2017-10-10'
union all
select *
from expenses
where date between '2017-10-6' and '2017-10-10';