MYSQL加入两个具有相同字段值的表字段,但如果另一个字段与另一个字段不匹配,则仍将包括

时间:2017-08-03 07:50:21

标签: php mysql sql-order-by

我今天读过很多MYSQL组合表,但它们都不符合我的问题。任何人都可以帮助我实现我的欲望结果,如下图所示?

表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...     |
|--------------------|

表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...     |
|--------------------|

我只想获得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`

我对该查询的问题是我使用:

     ON `tbl2`.`year` = `tbl1`.`year`

只会返回比赛年份。所以是的,我被困住了。

期望的结果:

|----------------------------|
|     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...         |
|----------------------------|

在这种情况下的问题是table2有2004而table1有2005,它们都没有另一个。但我仍然希望逐年显示它们。

如果单独使用查询无法完成,我也会接受PHP脚本来完成此操作,但查询是我关注的更多..

2 个答案:

答案 0 :(得分:2)

您正在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

答案 1 :(得分:0)

完整的答案是:

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