MySQL查询将三个表与不同的列和行组合在一起

时间:2017-04-27 05:47:52

标签: mysql

I have below three tables in database:

users:
id emailaddress
1 abc@sdfd.com
2 ghgf@fdgfs.com
3 hjfy@fcgfd.com
allowance_details
id user_id allowance date
1 1 13000 15/02/2017
2 1 10000 23/01/2016
3 2 25000 15/02/2017
4 3 15000 10/1/2017
5 3 7000 12/12/2015
bonus_details
id user_id bonus date
1 1 7000 15/02/2017
2 1 5000 17/01/2016
3 1 3500 23/07/2015
4 2 4500 10/1/2017
5 2 6000 16/03/2016
6 3 2500 18/6/2016
7 3 3800 24/09/2015
I want to combine above three tables and want below result: id emailaddress allowance date bonus date
1 abc@sdfd.com 13000 15/02/2017 7000 15/02/2017
1 abc@sdfd.com 10000 23/01/2016 5000 17/01/2016
1 abc@sdfd.com 3500 23/07/2015
2 ghgf@fdgfs.com 25000 15/02/2017 4500 10/1/2017
2 ghgf@fdgfs.com 6000 16/03/2016
3 hjfy@fcgfd.com 15000 10/1/2017 2500 18/6/2016
3 hjfy@fcgfd.com 7000 12/12/2015 3800 24/09/2015
3 hjfy@fcgfd.com 4000 12/7/2014
Any one help me out what will be the correct MySQL query to fetch such result? Below is my query: SELECT DISTINCT u.id, u.emailaddress, bon.bonus, bon.date,alw.allowance,alw.date FROM users u LEFT JOIN bonus_details bon ON bon.user_id = u.id LEFT JOIN allowance_details alw ON alw.user_id = u.id

1 个答案:

答案 0 :(得分:0)

请尝试以下:

从用户中选择u.id,u.emailaddress,aw.allowance,aw.date,bd.bonus,bd.date

内部联接allowance_Details aw.user_id = u.id

内部联接bonus_details bd on bd.user_id = u.id