MYSQL - 连接两个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3974185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:29:22  来源:igfitidea点击:

MYSQL - Concatenate two tables

sqlmysqlconcatenation

提问by databasedude

I have two tables as follows:

我有两个表如下:

    TABLE A                    TABLE B
 StuID | actid              FacID | actid
  3       12                  98      17
  5       17                  54      21

I want to list the name of everyone, both students and faculty, who participate in activity 17. Is there anyway I can get a result as below:

我想列出参加活动 17 的每个人的姓名,包括学生和教职员工。无论如何我可以得到如下结果:

 id  | actid
 98     17
 5      17

WITHOUT creating a new table (by just using nesting of expressions or derived relations) ?

无需创建新表(仅使用表达式或派生关系的嵌套)?

A JOIN on the actid would give something like:

actid 上的 JOIN 会给出类似的结果:

StuID  | FacID  | actid
 5        98        17

I guess I need a form of concatenation??

我想我需要一种连接形式?

回答by Thilo

select * from table_a where actid = 17
union all
select * from table_b where actid = 17

You may (or may not) need to do something about the ids not being unique, such as

您可能(或可能不需要)需要对不唯一的 id 做一些事情,例如

select 'Student', table_a.* from table_a where actid = 17
union all
select 'Faculty', table_b.* from table_b where actid = 17

回答by Joshua Martell

You want UNION ALL:

你想要联合所有:

(SELECT * FROM tablea) UNION ALL (SELECT * FROM tableb)

(SELECT * FROM tablea) UNION ALL (SELECT * FROM tableb)

I think those parenthese are correct. I remember MySQL being fussy about this.

我认为这些括号是正确的。我记得 MySQL 对此很挑剔。

回答by Harshal Bisht

its too easy select tableA.stuId,tableA.actId, tableB.facId,tableB.actIdfrom tableA,tableB where tableA.actid=tableB.actid;`

它太容易 select tableA.stuId,tableA.actId, tableB.facId,tableB.actId从 tableA,tableB 那里 tableA.actid=tableB.actid;`

回答by programmer master

You can concatenate these two tables by using select, fromand where.

您可以使用select,from和连接这两个表where