在Select中合并两个表(SQL Server 2008) [英] Combine Two Tables in Select (SQL Server 2008)

查看:324
本文介绍了在Select中合并两个表(SQL Server 2008)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个表,例如:

If I have two tables, like this for example:

表1(产品)

id
name
price
agentid

表2(代理)

userid
name
email

如何从包含代理商名称和电子邮件(即products.agentid = agent.userid)的产品中获取结果集?

How do I get a result set from products that include the agents name and email, meaning that products.agentid = agent.userid?

例如我如何加入SELECT WHERE price < 100?

推荐答案

已编辑以支持价格过滤器

您可以使用INNER JOIN子句来连接这些表.这样做是这样的:

You can use the INNER JOIN clause to join those tables. It is done this way:

select p.id, p.name as ProductName, a.userid, a.name as AgentName
from products p
inner join agents a on a.userid = p.agentid
where p.price < 100

另一种方法是通过WHERE子句:

Another way to do this is by a WHERE clause:

select p.id, p.name as ProductName, a.userid, a.name as AgentName
from products p, agents a
where a.userid = p.agentid and p.price < 100

请注意,在第二种情况下,您要对两个表的所有行进行自然乘积运算,然后对结果进行过滤.在第一种情况下,您需要在同一步骤中加入时直接过滤结果. DBMS将理解您的意图(不管您选择解决此问题的方式如何)并以最快的方式处理它.

Note in the second case you are making a natural product of all rows from both tables and then filtering the result. In the first case you are directly filtering the result while joining in the same step. The DBMS will understand your intentions (regardless of the way you choose to solve this) and handle it in the fastest way.

这篇关于在Select中合并两个表(SQL Server 2008)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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