Database 使用SQL在两个不同表的两列中搜索值?
我需要一个代码来搜索两个不同SQL表中两列中的值Database 使用SQL在两个不同表的两列中搜索值?,database,python-2.7,sqlite,Database,Python 2.7,Sqlite,我需要一个代码来搜索两个不同SQL表中两列中的值 a = raw_input('Enter name here') cur.execute('SELECT phone FROM participants') b = cur.fetchall() if a in b: print "The name is already exist" 在这里,我搜索了表格参与者。在两个表中搜索应该怎么做?假设您需要SQL语句,您只需要使用select from两个表而不是一个表。要将所有内容保存在单个
a = raw_input('Enter name here')
cur.execute('SELECT phone FROM participants')
b = cur.fetchall()
if a in b:
print "The name is already exist"
在这里,我搜索了表格参与者。在两个表中搜索应该怎么做?假设您需要SQL语句,您只需要使用select from两个表而不是一个表。要将所有内容保存在单个语句中,您可以使用UNION,如下所述: 假设您有第二个表,名为friends,电话字段也在其中 然后,您的SQL将如下所示:
SELECT phone FROM participants where name = <input name here>
UNION
SELECT phone FROM friends where name = <input name here>
SELECT phone FROM participants where name = <your input here> or lastname = <your input here>
UNION
SELECT phone FROM friends where name = <your input here> or lastname = <your input here>
如果这与您的案例相关,您可以在末尾添加sort。
通过添加or子句,您还可以在每个表中搜索多个列,如下所示:
SELECT phone FROM participants where name = <input name here>
UNION
SELECT phone FROM friends where name = <input name here>
SELECT phone FROM participants where name = <your input here> or lastname = <your input here>
UNION
SELECT phone FROM friends where name = <your input here> or lastname = <your input here>
当然,您必须替换为正确的搜索字符串。
顺便说一句,您提供的代码没有搜索任何内容-它只是将表中的所有电话转储到b变量中,这可能非常低效,尤其是当表变大时。我强烈建议通过SQL进行搜索,然后显示脚本的输出。什么是两个表?什么是两列?如果两列是两列,对于两个表,使用SQL Join,对于两列,使用Where子句