我正在研究一个项目。我有一个表tblhomework,其中有一列学生代码 - 其中包含用逗号分隔的学生代码。现在我有几个下拉搜索记录,其中是按学生名称搜索。现在我让我的学生代码在我的表中如何与学生姓名匹配。我使用以下查询,直到现在我使用学生代码匹配但现在我必须按学生姓名匹配
查询
string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode
FROM tblhomework
join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode
join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode
where tblhomework.StudentsCode like'" + studentcode + "';
以下是我得到的结果的屏幕截图
我有一张学生表,其中包含您可以使用的学生学生姓名。
答案 0 :(得分:1)
在当前SQL中使用FIND_IN_SET: -
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode
FROM tblhomework
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE FIND_IN_SET('" + studentcode + "', tblhomework.StudentsCode);
但是,如果学生代码列表中的逗号之前/之后没有空格,那么这不会起作用
要将其与学生姓名表联系起来(并对该表的布局做出假设),请使用以下内容: -
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode ,
tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsCode = '" + studentcode + "'
按学生姓名搜索(尽管通常情况下,如果下拉菜单返回数字唯一学生ID会更容易): -
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode ,
tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsName = '" + studentname + "'
答案 1 :(得分:0)
要在列中存储逗号分隔值是不好的设计,您应该查看Database Normalization并通过将所有相关的学生代码存储在联结表中来规范化您的结构,但是从上面的评论中您说可以'改变结构,所以在mysql中你可以使用FIND_IN_SET()并加入你的学生表,我不熟悉c#语法,所以我发布了mysql查询,也使用你的原始名称约定列
SELECT
DISTINCT
h.ID,
t.TEACHERNAME,
c.CLASSNAME,
h.Title,
h.HomeworkDetail,
h.StudentsCode
FROM
tblhomework h
JOIN tblclass c
ON c.CLASSCODE = h.ClassCode
JOIN tblteacher t
ON t.TSHORTNAME = h.Tshortcode
JOIN students s ON(FIND_IN_SET(s.StudentsCode, h.StudentsCode) > 0)
WHERE FIND_IN_SET('studentcode', h.StudentsCode) > 0
OR s.student_name LIKE 'test'
答案 2 :(得分:0)
您可以使用'FIND_IN_SET'
功能搜索逗号分隔的值集。
更改您的where子句如下:
where FIND_IN_SET( @student_code, tblhomework.studentscode );
使用AddWithValue
绑定从文本框中读取的'studentcode'
的值。
string studentcode = txt_studentcode.Text.ToString();
myCommand = new MySqlCommand( sql_query_string, connection );
myCommand.Parameters.AddWithValue( "@student_code", studentcode );
然后执行。