从SQL中的另一个表返回项目

时间:2012-05-29 14:58:14

标签: asp.net sql tsql

我正在努力让这个工作!我知道它简单......

我有一个充满工作的表和一个包含位置的表(为了能够动态添加新位置并填充下拉列表等。

我想要做的是在一个位置返回所有作业(不是问题),为它们分配一个与每个位置的ID相对应的位置ID(包含job_location_ID,job_Location_name,job_Location_Country)

sql = "SELECT  [job_ID],
        [job_ref],
        [job_title],
        [job_description],
        [job_location]
FROM    [Web_Xtr_HR]
WHERE   (
          ( [job_ext_int_both] = 1 )
          AND ( [job_location] = " + theIndex + " )
        )
ORDER BY [job_ID] DESC"

这将读取所有项目,因此我需要做的是,每个结果包括与另一个表中的job_Location_ID关联的job_Location_name([Web_Xtr_Job_Locations])

帮助!

4 个答案:

答案 0 :(得分:1)

您需要加入这两个表,以便从两个表中选择列。

SELECT  job_ID,
        job_title,
        job_Location_Name
FROM    Web_Xtr_HR
        INNER JOIN Web_Xtr_Job_Locations
            ON Web_Xtr_Hr.job_Location_ID = Web_Xtr_Job_Locations.job_LocationID
WHERE   job_ext_int_both = 1 -- Add more filters as needed.

INNER JOIN将返回两个表中都匹配的元素。要匹配的字段由ON行确定。

答案 1 :(得分:1)

"SELECT  [job_ID],
        [job_ref],
        [job_title],
        [job_description],
        [job_location]
FROM    [Web_Xtr_HR]
        INNER JOIN [Web_Xtr_Job_Locations]
            ON [Web_Xtr_HR].job.Location_ID = [Web_Xtr_HR]
WHERE   (
          ( [job_ext_int_both] = 1 )
          AND ( [job_location] = " + theIndex + " )
        )
ORDER BY [job_ID] DESC"

答案 2 :(得分:1)

使用内部联接:

"SELECT  [Web_Xtr_Job_Locations].job_Location_name,
        [Web_Xtr_HR].[job_ID],
        [Web_Xtr_HR].[job_ref],
        [Web_Xtr_HR].[job_title],
        [Web_Xtr_HR].[job_description],
        [Web_Xtr_HR].[job_location]
FROM    [Web_Xtr_HR]
        INNER JOIN [Web_Xtr_Job_Locations]
            ON [Web_Xtr_HR].job_location_id = [Web_Xtr_Job_Locations].job_location_id
WHERE   (
          ( [Web_Xtr_HR].[job_ext_int_both] = 1 )
          AND ( [Web_Xtr_HR].[job_location] = " + theIndex + " )
        )
ORDER BY [job_ID] DESC"

答案 3 :(得分:0)

谢谢大家,经过一段时间的混合后我最终得到了:

SELECT 
[Web_Xtr_HR].[job_ID], 
[Web_Xtr_HR].[job_ref], 
[Web_Xtr_HR].[job_title], 
[Web_Xtr_HR].[job_description], 
[Web_Xtr_HR].[job_location], 
[Web_Xtr_Job_Locations].[job_location_name], 
[Web_Xtr_Job_Locations].[job_location_country] 
FROM 
[Web_Xtr_HR]
    INNER JOIN [Web_Xtr_Job_Locations]
    ON [Web_Xtr_HR].[job_Location] = [Web_Xtr_Job_Locations].[job_Location_ID]
WHERE   
(([Web_Xtr_HR].[job_ext_int_both] = 1 )
AND
([Web_Xtr_HR].[job_location] = " + theIndex + "))

ORDER BY [Web_Xtr_HR].[job_ID] DESC