如何使用mysql连接两个不同值的表

jtoj6r0c  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(276)

我有两张table:
表1名称:购买

姓名 | 名称代码|编号|

  一          01        25
  一          01        25
  b          02        75
  c          03        100
  c          03        25
表2名称:sell

姓名 | 名称代码|编号|

  b          02        60
  b          02        40
  c          03        80
  c          03        40
  d          04        45
  d          04        50

那么,如何使两个表像这样连接起来(使用mysql查询):

姓名 | 名称代码|编号| 名称|名称代码|编号|

  一          01        50(总和)  无效的    无效的      无效的
  b          02        75        b        02      100(总和)
  c          03        125(总和)   c        03      120(总和)
  无效的      无效的       无效的      d        04        90(总和)
当我键入(sum)时,它意味着值是两行的和
因为这对我来说太难了,所以我非常需要帮助
请帮帮我,我不知道怎么做。非常感谢
如果我需要b<70或c<30等条件。。。

42fyovps

42fyovps1#

SELECT table_1.Name,table_1.Namecode ,SUM(table_1.Number),table_2.Name,

table_2.Namecode,SUM(table_2.Number)

FROM table_1 

FULL OUTER JOIN table_2

ON table_1.name = table_2.name

GROUP BY table_1.name,table_2.name
fxnxkyjh

fxnxkyjh2#

这有点尴尬,因为mysql不支持完全外部连接。由于错误而编辑:

SELECT B.name, B.name_code, B.total, S.name, S.name_code, S.total
FROM (
  SELECT name, name_code, SUM(number) AS total FROM buy GROUP BY name, name_code
) B LEFT JOIN (
  SELECT name, name_code, SUM(number) AS total FROM sell GROUP BY name, name_code
) S ON B.name = S.name
UNION
SELECT NULL, NULL, NULL, name, name_code, SUM(number) AS total FROM sell
WHERE name NOT IN (SELECT name FROM buy)
GROUP BY name, name_code;

相关问题