Запрос SQL для возврата данных из таблицы возврата таблицы ошибок (вероятно, из-за моего синтаксиса запроса!) - PullRequest
0 голосов
/ 13 октября 2019

У меня проблемы с моим SQL-запросом, чтобы получить какие-либо данные из моей базы данных, используя python / flask (возможно, из-за того, что я относительно новичок в 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, на предмет правильного синтаксиса, который можно использовать рядом с 'И курс_ КОД ИЗ курсов ЛЕВАЯ ПОДПИСКА на студента student_id = stud' в строке 1. Поиск не работает

Любой ився помощь будет очень ценится!

1 Ответ

0 голосов
/ 13 октября 2019

Это неправильный синтаксис для запроса JOIN. Попробуйте вместо этого:

SELECT s.student_id, s.first_name, s.last_name , c.course_code
FROM student s
LEFT JOIN enrollments e on e.student_id = s.student_id
JOIN courses c ON c.course_code = e.course_code 
WHERE CONCAT(s.first_name, s.last_name) LIKE '%{}%'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...