[英]MYSQL Join two table fields with same field value but will still include if the other field doesn't match the other one
A lot of MYSQL Combining tables i have read today, but none of them fits with my problem. 我今天读过很多MYSQL组合表,但它们都不符合我的问题。 can anyone help me achive my desire result like in below?
任何人都可以帮助我实现我的欲望结果,如下图所示?
TABLE 1:
表格1:
|--------------------| | tbl1 | |--------------------| |user_id|points|year | |--------------------| | 1 | 3.2 | 2001| | 1 | 2.2 | 2002| | 1 | 3.8 | 2003| | 1 | 3.6 | 2005| | 2 | 1.2 | 2001| | 2 | 1.2 | 2002| | 2 | 1.2 | 2003| | *etc... | |--------------------|
TABLE 2:
表2:
|--------------------| | tbl2 | |--------------------| |user_id|amount|year | |--------------------| | 1 | 6.2 | 2001| | 1 | 9.2 | 2002| | 1 | 2.8 | 2003| | 1 | 7.6 | 2004| | 2 | 3.2 | 2001| | 2 | 8.2 | 2002| | 2 | 6.2 | 2003| | *etc... | |--------------------|
i only want to get the user_id1 i have the following query, i tried many query combination but didn't get any. 我只想得到user_id1我有以下查询,我尝试了很多查询组合,但没有得到任何。
SELECT `tbl1`.`points`, `tbl2`.`amount`, `tbl1`.`year` FROM ( SELECT * FROM `tbl1` WHERE `user_id` = 1 ORDER BY `year` DESC ) AS `tbl1` INNER JOIN ( SELECT * FROM `tbl2` WHERE `user_id` = 1 ORDER BY `year` DESC ) AS `tbl2` ON `tbl2`.`year` = `tbl1`.`year`
my problem to that query is that i use: 我对该查询的问题是我使用:
ON `tbl2`.`year` = `tbl1`.`year`
which will only return the match year. 这只会返回比赛年份。 so yeah, i'm stuck.
所以是的,我被困住了。
DESIRED RESULT:
期望的结果:
|----------------------------| | JOINED/COMBINED | |----------------------------| |user_id|amount|points| year | |----------------------------| | 1 | 6.2 | 3.2 | 2001 | | 1 | 9.2 | 2.2 | 2002 | | 1 | 2.8 | 3.8 | 2003 | | 1 | 7.6 | Null | 2004 | | 1 | Null | 3.6 | 2005 | | *etc... | |----------------------------|
the problem in this case is that table2 has 2004 while table1 has 2005 both of them doesn't have another. 在这种情况下的问题是table2有2004年,而table1有2005年,它们都没有另一个。 but i still want to display them order by year.
但我仍然希望逐年显示它们。
If it can't be done with query alone i will also accept PHP scripting to make this done but Query is my concern here more.. 如果单独使用查询无法完成,我也会接受PHP脚本来完成这项工作,但查询是我关注的更多..
You are looking for a FULL OUTER JOIN
= LEFT + RIGHT JOIN
on MySQL
: 您正在寻找一个
FULL OUTER JOIN
= LEFT + RIGHT JOIN
MySQL
:
SELECT *
FROM tbl1
LEFT JOIN tbl2 ON tbl1.user_id = tbl2.user_id
AND tbl1.year = tbl2.year
UNION
SELECT *
FROM tbl1
RIGHT JOIN tbl2 ON tbl1.user_id = tbl2.user_id
AND tbl1.year = tbl2.year
The full answer will be: 完整的答案是:
select user_id, sum(points) as poins, sum(amount) as amount, year from (
SELECT tbl1.user_id, tbl1.points, tbl2.amount, tbl1.year
FROM tbl1
LEFT JOIN tbl2 ON tbl1.user_id = tbl2.user_id
AND tbl1.year = tbl2.year
UNION
SELECT tbl2.user_id,tbl1.points , tbl2.amount, tbl2.year
FROM tbl1
RIGHT JOIN tbl2 ON tbl1.user_id = tbl2.user_id
AND tbl1.year = tbl2.year) tables
group by year
order by year
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.