2

私はこのような声明を持っています:

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

問題はカラムフロアIDです。このクエリの結果は、フロアのIDを示しています。

このテーブルはfloor(30行程度)と呼ばれ、列IDとfloornumberがあります。floorid(上記のステートメント)の値は、テーブルフロアのIDと一致します。

上記のクエリで、floorid値をフロアテーブルのfloornumber列の関連する値に切り替えたいと思います。

誰かがこれを行う方法を教えてもらえますか?私はMicrosoftSQLServer2008r2を使用しています。

私はSQLを初めて使用するので、可能であれば明確で理解しやすい方法が必要です。

4

3 に答える 3

5
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
于 2012-08-01T15:05:19.550 に答える
1

You need to use a join.
This will join the two tables on a certain field.
This way you can SELECTcolumns from more than one table at the time.

When you join two tables you have to specify on which column you want to join them.
In your example, you'd have to do this:
from employee join floor on employee.floorid = floor.id

Since you are new to SQL you must know a few things. With the other enaswers you have on this question, people use aliases instead of repeating the table name.
from employee a join floor b
means that from now on the table employee will be known as a and the table floor as b. This is really usefull when you have a lot of joins to do.

Now let's say both table have a column name. In your select you have to say from which table you want to pick the column name. If you only write this
SELECT name from Employee a join floor b on a.id = b.id
the compiler won't understand from which table you want to get the column name. You would have to specify it like this :
SELECT Employee.name from Employee a join floor b on a.id = b.id
or if you prefer with aliases :
SELECT a.name from Employee a join floor b on a.id = b.id

Finally there are many type of joins.

  • Inner join ( what you are using because simply typing Join will refer to an inner join.
  • Left outer join
  • Right outer join
  • Self join
  • ...

To should refer to this article about joins to know how to use them correctly.
Hope this helps.

于 2012-08-01T15:19:49.630 に答える
1

フロアIDがフロアテーブルの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
于 2012-08-01T15:06:20.387 に答える