我在使用python/flask从数据库中获取数据时遇到了SQL查询问题(可能是因为我对MySQL比较陌生,而且我的查询语法可能很糟糕!)
我正在尝试从数据库的桥接表中获取数据,因为它是在下面创建的:
CREATE TABLE student (
student_id int AUTO_INCREMENT,
first_name varchar (20) NOT NULL,
last_name varchar (20) NOT NULL,
year_began int NOT NULL,
PRIMARY KEY (student_id)
);
CREATE TABLE courses (
course_code varchar (7) NOT NULL,
course_title varchar (100) NOT NULL,
year_delivered int NOT NULL,
PRIMARY KEY (course_code)
);
CREATE TABLE enrollments (
student_id int NOT NULL,
course_code varchar (7) NOT NULL,
CONSTRAINT enrollment PRIMARY KEY (student_id, course_code),
FOREIGN KEY (student_id) REFERENCES student (student_id),
FOREIGN KEY (course_code) REFERENCES courses (course_code)
);
我当前的python代码(包括我的查询)是这样编写的:
student_name = str(request.form['student_name_search'])
student_name = ' '.join(student_name.split())
try:
cursor = mydb.cursor()
cursor.execute("SELECT student_id, first_name, last_name FROM student AND course_code FROM courses\
LEFT JOIN enrollments on student_id=student_id LEFT JOIN course_code=course_code WHERE\
(CONCAT(first_name,last_name ) LIKE '%{}%')".format(student_name))
search_result = cursor.fetchall()
cursor.close()
return render_template('studentselect_results.html', student_name = student_name)
except mysql.connector.Error as err:
cursor.close()
return failure('studentsearch',f"Error message: {err}. Search didn't work")
输入搜索条件的HTML如下:
<form action="{{ url_for('process_searchstudent') }}" method="POST">
<div class="form-row justify-content-center">
<div class="form-row">
<div class="form-group col-12">
<input type="text" class="form-control" id="student_name_search" name="student_name_search"
placeholder="Enter Students Name">
</div>
</div>
</div>
<!-- SUMBIT/RESET BUTTONS-->
<div class="form-row justify-content-center">
<div class="form-group row">
<div class="form-group">
<input type="submit" class="btn btn-outline-success" value="Search">
<input type="button" id="resetBtn" class="btn btn-outline-danger" value="Reset">
</div>
</div>
</div>
</form>
我希望查询返回数据的HTML如下:
<table class="table table-sm table-striped">
<thread class="thread-light">
<tr>
<th>Student ID:</th>
<th>Student First Name:</th>
<th>Student Last Name:</th>
<th>Click to View Student Details</th>
</tr>
</thread>
<tbody>
{% for each_result in search_results %}
<tr>
<td>{{item[0]}}</td>
<td>{{item[1]}}</td>
<td>{{item[2]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
在第一个HTML页面上单击“搜索”按钮时,会出现以下错误:
错误消息:1064(42000):您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以获取正确的语法,以便在第1行中使用near'和course\u code FROM courses LEFT JOIN registrations on student\u id=stud'。搜索不起作用
任何帮助都将不胜感激
这不是
JOIN
查询的正确语法。请尝试以下操作:相关问题 更多 >
编程相关推荐