使用1个表中的数据查询另一个表

时间:2017-06-02 04:12:25

标签: sql-server linq

我有2张桌子。我想使用NAME表中的'First_Name'和'Middle_Name'来获取DESCRIPTION表中的'Description'。我可以知道如何在SQL和LINQ表达式中构造此查询!非常感谢!

CREATE TABLE NAME (
    TICKET_ID int NOT NULL,
    First_Name varchar(255),  
    Middle_Name varchar(255),
    PRIMARY KEY (NAME )
);

INSERT INTO @NAME VALUES
(1, 'alex', 'black' ),
(2, 'john', 'hudson'),
(3, 'alice', 'channing')


CREATE TABLE description(
    description_id int NOT NULL,
    First_Name varchar(255),  
    Middle_Name varchar(255),
    Description varchar(255),
    PRIMARY KEY (description_id )
);

INSERT INTO @description
(1, 'alex', 'black' , 'tall'),
(2, 'john', 'hudson', 'strong'),
(3, 'alice', 'channing', 'short')

2 个答案:

答案 0 :(得分:1)

CREATE TABLE #NAME (
    TICKET_ID int NOT NULL,
    First_Name varchar(255),  
    Middle_Name varchar(255),

);

INSERT INTO #NAME VALUES
(1, 'alex', 'black' ),
(2, 'john', 'hudson'),
(3, 'alice', 'channing')


CREATE TABLE #description(
    description_id int NOT NULL,
    First_Name varchar(255),  
    Middle_Name varchar(255),
    Description varchar(255),
    PRIMARY KEY (description_id )
);

INSERT INTO #description values
(1, 'alex', 'black' , 'tall'),
(2, 'john', 'hudson', 'strong'),
(3, 'alice', 'channing', 'short')

select Description from #NAME A  join
 #description B on  b.First_Name=a.First_Name  
 and b.Middle_Name=a.Middle_Name

答案 1 :(得分:1)

sql:

select d.Description from #description d join #name n on d.First_name=n.first_name and d.last_name=n.last_name

Linq:

from d in description join n in name on new on new { d.First_name, d.last_name } equals new { n.first_name, n.last_name } select new { d.Description}