如何在 SQL 中从两个不同的表中选择值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8881713/
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-09-01 14:01:55  来源:igfitidea点击:

How to select values from two different tables in SQL

sqlsql-server

提问by

I have two tables in my SQL Server database. The first is Test1and second is Test2. There is a column RegNoin both tables.

我的 SQL Server 数据库中有两个表。第一个是Test1,第二个是Test2RegNo两个表中都有一列。

Now I want to select the values from both the tables for a particular RegNo.

现在我想从两个表中为特定的RegNo.

This is what I'm doing

这就是我正在做的

SELECT Test1.SurName, Test2.Class, Test2.Medium
FROM Test1,Test2 JOINS
Test2 ON Test1.RegNo = Test2.RegNo

But my query is giving error.

但我的查询给出了错误。

采纳答案by Eugen Rieck

SELECT Test1.SurName, Test2.Class, Test2.Medium
FROM Test1 
INNER JOIN Test2 ON Test1.RegNo = Test2.RegNo

回答by

select
    Test1.SurName,
    Test2.Class,
    Test2.Medium
from Test1
inner join Test2
on Test1.RegNo = Test2.RegNo

And if you want to select your data for a particular RegNo, just add a WHEREclause to the end, like so:

如果您想为特定的 选择数据RegNo,只需WHERE在末尾添加一个子句,如下所示:

select
    Test1.SurName,
    Test2.Class,
    Test2.Medium
from Test1
inner join Test2
on Test1.RegNo = Test2.RegNo
where Test1.RegNo = 123456   -- or whatever value/datatype your RegNo is

回答by Taryn

SELECT Test1.SurName, Test2.Class, Test2.Medium
FROM Test1
INNER JOIN Test2
ON Test1.RegNo = Test2.RegNo

please see a visual explanation of joinsthis is very helpful in learning joins.

请查看连接的可视化说明,这对学习连接非常有帮助。

回答by Marco

Try this:

尝试这个:

SELECT Test1.SurName, Test2.Class, Test2.Medium
FROM Test1 INNER JOIN Test2
ON Test1.RegNo = Test2.RegNo
WHERE Test1.RegNo = desired_id

回答by Andreas Rohde

Very Basic question, try google next time and this now:

非常基本的问题,下次试试谷歌,现在试试:

SELECT Test1.SurName, Test2.Class, Test2.Medium
FROM Test1
inner join Test2 ON Test1.RegNo = Test2.RegNo

回答by Sam M

Here is your query with correction.

这是您的更正查询。

SELECT Test1.SurName, Test2.Class, Test2.Medium
    FROM Test1 INNER JOIN Test2 ON Test1.RegNo = Test2.RegNo where  Test2.RegNo=Test1.RegNo;

Also you can filter the query by providing the RegNo,on whichEver table u want.

您也可以通过提供您想要的 RegNo 来过滤查询。

回答by kontashi35

If you are looking foe method without join and relation.This will do the trick.

如果您正在寻找没有连接和关系的敌人方法。这将解决问题。

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

其中 dual 是一个带有单列的虚拟表——任何东西都只需要表来查看