使用Intersect从两个表中获取记录

时间:2012-12-07 12:42:09

标签: sql intersect

我希望获得特定部分的学生列表以及其他搜索条件。我这样做: -

declare @sectionId int, @name varchar
select @sectionId=23
select @name='a'

select UserId, FirstName from StudentMaster
Where FirstName Like @name and UserId IN
(
  select UserId from StudentMaster
  Intersect
  select StudentId from StudentInSections where SectionId=@sectionId
)

但它没有给出正确答案。如果我只写Userid条件它工作正常但我必须得到整个搜索条件的列表。 有人帮我吗?

2 个答案:

答案 0 :(得分:0)

select sm.UserId, sm.FirstName from StudentMaster sm
    inner join StudentInSections ss on ss.StudentId = sm.UserId
Where sm.FirstName Like @name
    and ss.SectionId = @sectionId

这样的事情应该有用。您只需要学习如何使用内连接。

答案 1 :(得分:0)

问题是LIKE操作数。如果@name'a',则只返回名称为'a''A'的学生。如果您希望学生姓名以“a”开头,则必须添加通配符“%”

FirstName LIKE 'a%'

(某些SQL方言如MS Access使用通配符“*”而不是“%”。)

关于区分大小写/不敏感搜索的注释。根据SQL方言和用于列的排序规则,搜索将区分大小写或不区分大小写。如果您不想进行区分大小写搜索(即您希望查找名称以“a”或“A”开头的学生),则可以执行以下操作:

UPPER(FirstName) LIKE 'A%'

或者在SQL-Server上

FirstName COLLATE UTF8_GENERAL_CI LIKE '%a'

CI表示不区分大小写。