2011-06-03 66 views
0

我有一個MS SQL 2008的表稱爲「水果」,看起來像這樣:如何加入表格並更改返回列的名稱?

id name   category_id 
-- ------------ ----------- 
1 Apples     4 
2 Bananas     6 
3 Crackers     6 

和所謂的「類別」與另一個表:

id category_name 
-- ------------- 
4 Foo 
6 Bar 

如何產生一個查詢,將返回的結果是這樣的:(列必須正好這個名字,因爲我想寫一個CSV)

fruit_name fruit_category_name 
---------- ------------------- 
Apples  Foo 
Bananas  Bar 
Crackers Bar 

+0

使用'AS'(別名)關鍵字。 – 2011-06-03 12:14:54

回答

8
SELECT f.name AS fruit_name, c.category_name AS fruit_category_name 
FROM fruits AS f 
INNER JOIN categories AS c ON c.id = f.category_id 
1
select name as fruit_name, category_name as fruit_category_name 
from fruits 
inner join categories on (fruits.category_id = categories.id) 
order by fruit_name 
2

試試這個:

SELECT f.name AS fruit_name, c.category_name AS fruit_category_name 
FROM fruits f INNER JOIN categories c 
ON f.id = c.id 
ORDER BY f.name 
0
SELECT fruits.name AS fruit_name, categories.category_name AS fruit_category_name FROM fruits INNER JOIN categories ON (fruits.category_id = categories.category_name) 
0

像這樣的事情?:

SELECT 
    f.name AS fruit_name, 
    c.category_name AS fruit_category_name 
FROM 
    fruits f 
JOIN 
    categories c ON c.id = f.category_id 
ORDER BY 
    fruit_name DESC 
0

您可以通過以下兩種方式之一重命名列:

SELECT 
    ColumnName AS DisplayName 
    FROM ... 

SELECT 
    DisplayName = ColumnName 
    FROM ... 

記住,使用[]如果你需要使用特殊字符(如空格)的顯示名稱中:

SELECT 
    ColumnName AS [Display Name] 
    FROM ... 

SELECT 
    [Display Name] = ColumnName 
    FROM ... 

你可以做你的加入是這樣的:

SELECT 
    f.name AS fruit_name 
     ,c.category_name AS fruit_category_name 
    FROM Fruits    f 
    INNER JOIN Categories c ON c.id=f.category_id 
相關問題