我有FACULTY表,其中包含其他表格的列,以逗号分隔。我想加入各自的表格。
faculty
表:
id | name | course_id | subject_id
a | smith | 2,3 | 1,2
course
表:
id | name
1 | bcom
2 | mcom
3 | bba
subject
表:
id | name
1 | account
2 | state
3 | economics
我想从这些表中获得结果,如..
faculty.id, faculty.name, course.name(using faculty.course_id), subject.name(using faculty.subject_id)
我已经尝试了很多查询,也发现了谷歌,但它并没有给我正确的结果。
答案 0 :(得分:1)
我认为表现不会太好但值得尝试。此解决方案适用于SQL SERVER
:
SELECT *
FROM faculty F
JOIN course C
ON ','+F.course_id+',' LIKE '%,'+CONVERT(VARCHAR,C.ID) +',%'
JOIN subject S
ON ','+F.subject_id_id+',' LIKE '%,'+CONVERT(VARCHAR,S.ID) +',%'
基于Albin Sunnanbo
的评论,我还建议您添加一些太多的表:
<强> fcourses 强>
facultyId
courseId
和
<强> fsubjects 强>
facultyId
subjectId
这样你就可以进行正确的加入:
SELECT *
FROM faculty F
JOIN fcourses FC
ON F.Id = FC.facultyId
JOIN course C
ON FC.courseId = C.ID
JOIN fsubjects FS
ON F.Id = FS.facultyId
JOIN subject S
ON FS.courseId = S.ID
答案 1 :(得分:0)
我做过类似的事情:
select f.id, f.lname, f.fname, U.useridlist
from TABLE1 F, TABLE2 U
where ',' || U.useridlist || ',' like '%,' || f.id || ',%'
答案 2 :(得分:0)
如果你可以创建一个'string to int table'函数,我会看看以下内容:
创建功能
CREATE FUNCTION [dbo].[udf_ConvertIntListToTable] (@list varchar(MAX))
RETURNS @tbl TABLE (val int) AS
BEGIN
DECLARE @ix int,
@pos int,
@str varchar(MAX),
@num int
SET @pos = 1
SET @ix = 1
WHILE @ix > 0
BEGIN
SET @ix = charindex(',', @list, @pos)
IF @ix > 0
SET @str = substring(@list, @pos, @ix - @pos)
ELSE
SET @str = substring(@list, @pos, len(@list))
SET @str = ltrim(rtrim(@str))
IF @str LIKE '%[0-9]%' AND
(@str NOT LIKE '%[^0-9]%' OR
@str LIKE '[-+]%' AND
substring(@str, 2, len(@str)) NOT LIKE '[-+]%[^0-9]%')
BEGIN
SET @num = convert(int, @str)
INSERT @tbl (val) VALUES(@num)
END
SET @pos = @ix + 1
END
RETURN
END
然后使用CROSS APPLY
进行查询declare @FacultyTable table(id int PRIMARY KEY, name nvarchar(50), course_id varchar(50))
declare @CourseTable table(id int PRIMARY KEY, name nvarchar(50))
insert into @FacultyTable values(1, 'Peter Sagal', '11,22')
insert into @FacultyTable values(2, 'Carl Kasell', '22,33')
insert into @CourseTable values(11,'News')
insert into @CourseTable values(22,'News')
insert into @CourseTable values(33,'News')
insert into @CourseTable values(44,'News')
select *
from @FacultyTable f
CROSS APPLY(
SELECT *
FROM @CourseTable c
WHERE
c.id IN (SELECT * FROM dbo.udf_ConvertIntListToTable(f.course_id))
) tCourses
答案 3 :(得分:0)
您可以执行以下查询
select * from faculty F
JOIN course C
on CHARINDEX((','+CAST(c.id as varchar(10))+','), (','+f.courseid+',')) > 0
JOIN subject s
on CHARINDEX((','+CAST(s.id as varchar(10))+','), (','+f.subjectid+',')) > 0