如何加入表并更改返回列的名称?

时间:2011-06-03 12:12:40

标签: sql-server sql-server-2008

我有一个名为“fruits”的MS SQL 2008表,如下所示:

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

和另一个名为“categories”的表格:

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

如何生成将返回如下结果的查询:

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

(列必须是那个名称,因为我正在尝试编写CSV。)

6 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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)

答案 4 :(得分: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

答案 5 :(得分: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