如何从Mysql中两个不同的表中选择内容? [英] How to select content from two different tables in Mysql?

查看:231
本文介绍了如何从Mysql中两个不同的表中选择内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择位于mysql数据库中不同表中的两列的内容?

解决方案

您将需要使用JOIN或UNION/UNION ALL.

这取决于您的要求.

假设您要在单独的行中使用表1列a 表2列b 中的所有值

您可以使用

SELECT ColA
FROM TABLE1
UNION ALL
SELECT ColB
FROM TABLE2

所有不同的值

SELECT ColA
FROM TABLE1
UNION
SELECT ColB
FROM TABLE2

并且假设您要在同一行中显示它们,它们应该具有一些链接它们的键

SELECT ColA, ColB
FROM TABLE1 t1 INNER JOIN
   TABLE2 t2 ON t1.ID = t2.ID

请注意,有不同类型的 SQL连接

不同的SQL联接

  • JOIN:位于时返回行 两个表中至少有一个匹配项
  • 左联接:从中返回所有行 左桌子,即使没有 右表中的匹配项
  • RIGHT JOIN:从中返回所有行 正确的桌子,即使没有 左侧表格中的匹配项
  • 完全联接:存在时返回行 一张桌子中的一个匹配项

How can I select the contents of two columns that reside in different tables in a mysql database?

解决方案

You would need to use either a JOIN or UNION/UNION ALL.

This will depend on wht you require.

Lets say you want all values from table 1 col a and table 2 col b in seperate rows

You can use

SELECT ColA
FROM TABLE1
UNION ALL
SELECT ColB
FROM TABLE2

All Distinct Values

SELECT ColA
FROM TABLE1
UNION
SELECT ColB
FROM TABLE2

And lets say that the you want to display them in the same row, they should have some key that links them

SELECT ColA, ColB
FROM TABLE1 t1 INNER JOIN
   TABLE2 t2 ON t1.ID = t2.ID

It would also be good to note that there are different types of Sql Joins

Different SQL JOINs

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

这篇关于如何从Mysql中两个不同的表中选择内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆