简体   繁体   English

如何从两个表中获取特定记录

[英]how to get specific records from two tables

I have 2 tables, table one contains phone numbers and owner name, and table two have phone , name and also its have city and street.我有 2 张桌子,一张桌子包含电话号码和所有者姓名,第二张桌子有电话,姓名,还有城市和街道。 the problem in table two is that the owner name is the name of the one who pays for the phone number and not the actual owner (for example if my dad pays for my phone number, his name will appear along side my number).表二中的问题是所有者姓名是支付电话号码的人的姓名,而不是实际所有者的姓名(例如,如果我父亲为我的电话号码付费,他的姓名将出现在我的号码旁边)。 what i want to do is to write a query that checks if the phone number exists on both tables and if it does, i want to see the owner name from table one and the other info from table two.我想要做的是编写一个查询,检查电话号码是否存在于两个表中,如果存在,我想查看表一中的所有者姓名和表二中的其他信息。

also if there is a number that exists only on table two i want to see it to.此外,如果有一个数字只存在于表二,我想看到它。 and if the number is only on table one i want to see it also but with the address and city column empty.如果数字只在第一张桌子上,我也想看到它,但地址和城市列是空的。

example for expected result:预期结果示例:

在此处输入图片说明

i have no idea how to do this, it will be very helpful if someone could tell me where to look for answer.我不知道该怎么做,如果有人能告诉我在哪里寻找答案会很有帮助。

You want a full join .你想要一个full join A simple method to implement this with SQLite is to use union all :使用 SQLite 实现这一点的一个简单方法是使用union all

select t2.address, t2.city, t1.phone, t1.name
from table1 t1 left join
     table2 t2
     using (phone)
union all
select t2.address, t2.city, t2.phone, t2.name
from table2 t2
where not exists (select 1 from table1 t1 where t1.phone = t2.phone);

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

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