Mentor table
------------
name (varchar)
contact (int)
english (boolean)
french (boolean)
german (boolean)
Student table
-------------
name (varchar)
contact (int)
english (boolean)
french (boolean)
german (boolean)
我想根据语言将导师与学生匹配,例如:
如果导师1懂英语和法语,他将与所有至少懂英语或法语的学生配对。
mentor1 (english, french)
-------------------------
studentA (english);
studentB (english, french);
studentC (english, german);
studentD (english, french, german)
如果导师2只知道德语,他将与所有至少知道德语的学生匹配。匹配的学生不仅仅知道德语。
mentor2 (german)
----------------
studentC (english, german)
studentD (english, french, german)
通常我只会使用一堆if then else
拼凑一个sql字符串,但我使用gridview
来显示数据,所以我不知道该怎么做。
示例代码和教程总是受欢迎的。
编辑:忘了提及mentor
表格还会包含name
和contact
等列。因此gridview
上的输出应为每mentor
一行。
答案 0 :(得分:5)
Select
m.MentorName
, m.Language
, s.StudentName
from Mentor as m
inner join Student as s
on (m.English = 1 and m.English = s.English)
or (m.french = 1 and m.French = s.French)
or (m.German = 1 and m.German = s.German);
如果你的表格没有每个语言的字段而是一个记录而不是
,这会更容易Table: Mentor(MentorName, Language)
Rows:
Mentor1 | English
Mentor2 | Englisn
Mentor2 | French
为学生做同样的事情,然后查询是:
Select
m.MentorName
, m.Language
, s.StudentName
from Mentor as m
inner join Student as s
on m.Language = s.Language
这里的好处是,如果您添加另一种语言,它纯粹是数据输入,无需更改表结构或代码,但这并不总是一种选择。
答案 1 :(得分:1)
SELECT m.*, s.name
FROM dbo.Mentor m
JOIN dbo.Student s
ON EXISTS
(
SELECT x.LanguageID
FROM
(
SELECT 1 AS LanguageID WHERE s.english = 1 UNION ALL
SELECT 2 AS LanguageID WHERE s.french = 1 UNION ALL
SELECT 3 AS LanguageID WHERE s.german = 1
) x
INTERSECT
SELECT y.LanguageID
FROM
(
SELECT 1 AS LanguageID WHERE m.english = 1 UNION ALL
SELECT 2 AS LanguageID WHERE m.french = 1 UNION ALL
SELECT 3 AS LanguageID WHERE m.german = 1
) y
)
ORDER BY m.name