简体   繁体   English

sqlite3如何同时搜索多个表?

[英]How to search multiple tables at the same time in sqlite3?

I'm tying to design a Sign In page.我正在设计一个登录页面。 I have three tables students , professors , dean .我有三桌studentsprofessorsdean I want to fetch the password for the given username and check if it's correct.我想获取给定用户名的密码并检查它是否正确。 I can do this for one table with:我可以为一张桌子做到这一点:

def get_password_by_username(username):
    c.execute("SELECT password FROM students WHERE username = :username", {"username": username})
    return c.fetchone()

How can I search for the username in all three tables at the same time?如何同时在所有三个表中搜索用户名? thanks.谢谢。

This query:这个查询:

SELECT username, password FROM students 
UNION ALL
SELECT username, password FROM professors
UNION ALL
SELECT username, password FROM dean

returns all the usernames and passwords from the 3 tables and you can filter to get the password like this:返回 3 个表中的所有用户名和密码,您可以过滤以获取密码,如下所示:

SELECT password
FROM (
  SELECT username, password FROM students 
  UNION ALL
  SELECT username, password FROM professors
  UNION ALL
  SELECT username, password FROM dean
)
WHERE username = :username

If you want to get all the data associated with some student based on student's username , you should use JOIN in your SQL queries to achieve that.如果您想根据学生的username获取与某个学生相关的所有数据,您应该在 SQL 查询中使用JOIN来实现。 You will maybe have to redesign your database a little bit to be able to get all the data you need.您可能需要稍微重新设计数据库才能获得所需的所有数据。

There are plenty of nice guides around about how to use JOIN ( this one or this one ), read them to understand better how to join your tables in a desired way.关于如何使用JOIN这个这个)有很多很好的指南,阅读它们以更好地了解如何以所需的方式加入您的表。

Very simple example:非常简单的例子:

SELECT 
    *
FROM 
    students s
LEFT JOIN professors p 
    ON s.professorID = p.professorID
WHERE
    s.username = 'some_username';

You can separate them with a comma你可以用逗号分隔它们

def get_password_by_username(username):
    c.execute("SELECT password FROM students, professors, dean WHERE username=?", (username,)
    return c.fetchone()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM