Combine Two Tables in Select (SQL Server 2008)(在 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Select 中合并两个表 (SQL Server 2008)


- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01