SQL SELECT基于单个查询中三个可能条件之一

时间:2019-02-13 20:51:19

标签: python sql sqlalchemy

我是SQL新手。当前正在完成课程“使用Python和Javascript进行CS50 Web编程”的第二个挑战。我的任务是建立一个书评网站,用户可以在搜索页面上通过书名或作者或isbn进行搜索。目前,我已经设置了此SQL,但看起来有点难看。我的问题是,有没有更优雅的方法来实现这一目标?理想情况下是在单个SQL查询中。

    page = request.form.get("page")
    searchText = request.form.get("searchText")
    bookAttr = request.form.get("bookAttr")
    likesearchText = "%" + searchText + "%"

    # Search results fixed to 10 per page

    if bookAttr == "isbn":
        rows = db.execute("SELECT isbn, title, author, year FROM books WHERE isbn LIKE :isbn LIMIT :start OFFSET :off",
                          {"isbn": likesearchText, "start": 10, "off": int(page) * 10}).fetchall()
    elif bookAttr == "title":
        rows = db.execute("SELECT isbn, title, author, year FROM books WHERE title LIKE :title LIMIT :start OFFSET :off",
                          {"title": likesearchText, "start": 10, "off": int(page) * 10}).fetchall()
    else:
        rows = db.execute("SELECT isbn, title, author, year FROM books WHERE author LIKE :author LIMIT :start OFFSET :off",
                          {"author": likesearchText, "start": 10, "off": int(page) * 10}).fetchall()

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

SELECT isbn, title, author, year
FROM books
WHERE isbn LIKE :isbn OR title LIKE :title OR author LIKE :author;

如果两个参数为NULL或空字符串,这将很好地工作。

答案 1 :(得分:0)

这实际上不是SQL解决方案...但是您是否考虑过动态设置value列?这样的东西(未经测试):

page = request.form.get('page')
searchText = request.form.get('searchText')
bookAttr = request.form.get('bookAttr')
# Avoid SQL injection vulnerability by checking the parameter value
if bookAttr != 'isbn' and bookAttr != 'title' and bookAttr != 'author':
    raise ValueError('Unsupported bookAttr: ' + bookAttr)
rows = db.execute('SELECT isbn, title, author, year FROM books WHERE '
                  + bookAttr
                  + ' LIKE :searchText LIMIT :start OFFSET :off',
                  {'searchText': '%' + searchText + '%', 'start': 10,
                  'off': int(page) * 10}).fetchall()