如何使用2个不同表中的where子句检索数据

时间:2013-03-29 16:09:04

标签: asp.net sql gridview

我有两张桌子[basic]& [info]都有一个主键email_id。现在我想从basic表中检索信息,但where子句应该具有来自两个表的搜索条件

示例:

SELECT DISTINCT 
    basic.f_name, 
    basic.l_name 
FROM 
    basic 
CROSS JOIN 
    info 
WHERE 
    (basic.email_id = basic.email_id) 
    AND (basic.caste LIKE '%' + @caste + '%') 
    AND (info.diet =  @diet )

(此查询用asp编写,用于gridview但不起作用)

3 个答案:

答案 0 :(得分:6)

SELECT basic.f_name, basic.l_name 
FROM basic INNER JOIN info ON basic.email_id = info.email_id 
WHERE (basic.caste LIKE '%' + @caste + '%') AND (info.diet = @diet )

答案 1 :(得分:1)

当您进行内部联接时,实际上您正在使用带有where子句的交叉联接。在内部联接中,所有数据被组合(笛卡尔积),然后使用where子句进行过滤。因此,我认为使用内部联接可以使代码更清晰。

SELECT DISTINCT basic.f_name, basic.l_name 
FROM basic 
CROSS JOIN info 
WHERE (basic.email_id = basic.email_id) 

相当于

SELECT basic.f_name, basic.l_name 
FROM basic INNER JOIN info ON basic.email_id = info.email_id 

我认为这可以解决您的问题。

答案 2 :(得分:0)

使用INNER JOIN

SELECT DISTINCT 
    basic.f_name, 
    basic.l_name 
FROM 
    basic as basic
INNER JOIN 
    info as info 
    ON basic.email_id = info.email_id
WHERE 
    (basic.caste LIKE '%' + @caste + '%') 
    AND (info.diet =  @diet )