【问题标题】:sql server - how to modify values in a query statement?sql server - 如何修改查询语句中的值?
【发布时间】:2012-07-30 12:21:13
【问题描述】:

我有这样的声明:

select lastname,firstname,email,floorid 
from employee 
where locationid=1 
    and (statusid=1 or statusid=3) 
order by floorid,lastname,firstname,email

问题是列 floorid。此查询的结果是显示楼层的 id。

有一个名为 floor 的表(大约有 30 行),其中包含列 id 和 floornumber。 floorid(在上面的语句中)值与表 floor 的 id 匹配。

我希望上面的查询将 floorid 值切换为 floor 表中 floornumber 列的关联值。

谁能告诉我如何做到这一点? 我正在使用 Microsoft sql server 2008 r2。

我是sql新手,如果可能的话,我需要一个清晰易懂的方法。

【问题讨论】:

  • 我建议您阅读joins,而不是直接回答您。数据库的优势不在于存储数据,它能够创建相关数据,然后您可以检索这些数据。为了检索相关数据,您 join 在您想要的任何列/标准上。这是 RDBMS(R = 关系)的基本方面之一,因此实际上只是熟悉您可用的工具(我建议阅读一些在线教程,可能是一两本书)。

标签: sql sql-server select sql-server-2008-r2


【解决方案1】:
select   lastname,
         firstname,
         email,
         floor.floornumber
from     employee
inner join floor on floor.id = employee.floorid
where    locationid = 1
         and (statusid = 1 or statusid = 3)
order by floorid, lastname, firstname, email

【讨论】:

    【解决方案2】:

    如果 floorid 与地板表的 id 匹配,您必须在检查位置进行简单的连接。然后你使用表层的楼层号。

    select a.lastname,a.firstname,a.email,b.floornumber 
    from employee a
    join floor b on a.floorid = b.id
    where a.locationid=1 and (a.statusid=1 or a.statusid=3) 
    order by a.floorid,a.lastname,a.firstname,a.email
    

    【讨论】:

    • @omega 如果您需要有关其工作原理的更多信息,您应该参考我的回答。
    • 我还有一个问题,如果员工表中的 floorid 值为 NULL,则该行将被跳过,因为 floor 表中没有名为 NULL 的 id。如何将其包含在查询中,其中值应保持为 NULL?
    • 使用“左连接”在 floorid 列中包含 null 行
    【解决方案3】:

    您需要使用join
    这将在某个字段上连接两个表。
    这样您就可以同时从多个表中SELECTcolumns。

    当您连接两个表时,您必须指定要连接它们的列。
    在您的示例中,您必须这样做:
    from employee join floor on employee.floorid = floor.id

    由于您是 SQL 新手,因此您必须了解一些事情。对于您在这个问题上的其他 enaswer,人们使用 aliases 而不是重复表名。
    from employee a join floor b
    意味着从现在开始,桌子上的员工将被称为a,桌子的地板被称为b。当您有很多连接要做时,这非常有用。

    现在假设两个表都有一个列name。在您的选择中,您必须说出要从哪个表中选择列名。如果你只写这个
    SELECT name from Employee a join floor b on a.id = b.id
    编译器无法理解您要从哪个表中获取列name。您必须像这样指定它:
    SELECT Employee.name from Employee a join floor b on a.id = b.id
    或者如果您更喜欢使用别名:
    SELECT a.name from Employee a join floor b on a.id = b.id

    最后有很多类型的连接。

    • 内连接(您使用的是什么,因为只需输入Join 将引用内连接。
    • 左外连接
    • 右外连接
    • 自加入
    • ...

    请参考this article about joins 了解如何正确使用它们。
    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 2021-07-28
      • 2018-09-23
      相关资源
      最近更新 更多