简体   繁体   English

从sql db中的多个表中提取数据

[英]extracting data from multiple tables in sql db

Hi i have a database which consists of 2 tables 嗨,我有一个包含2个表的数据库

userData table userData表

userID  |  userPass | Firstname |  Surname | Status | IPAddress
--------------------------------------------------------------  
110110  |  123456   | James     |  Jackson | Online |  11.112.1

contacts table 联系人表

    userID  |  contactID |
    --------------------- 
    110110  |  112114    |
    112112  |  110110    |
    110110  |  112444    |

The first table is the userdata table which I am using with my java application for login. 第一个表是我正在与Java应用程序一起使用进行登录的userdata表。 I also have another table which stores the users contacts , I am trying to write a query to allow me to take the users contacts and display them by the first name, surname and ID in a JList, I am extremely puzzled any help would be appreciated. 我还具有另一个存储用户联系人的表,我试图编写一个查询以允许我获取用户联系人并在JList中按名字,姓氏和ID显示它们,我非常困惑任何帮助将不胜感激。 I had a look at inner joins but seem to be getting more stuck. 我看过内部联接,但似乎越来越卡住了。 how can I construct a query to get the data i need? 如何构造查询以获取所需的数据? I am also trying to make a separate query to display only the online users. 我也在尝试进行单独的查询以仅显示在线用户。

ok i have managed to use the following query: 好的,我设法使用以下查询:

SELECT userName
FROM userdata, contacts
WHERE userID = "110110" AND userData.userID = contacts.contactID

This is taking the userID "110110" from the contacts tables and the contactID's which correspond and returning the userName (from the userdata table)of the contacts. 这是从联系人表中获取用户ID“ 110110”以及与之对应的contactID,并返回联系人的userName(来自userdata表)。 i have encountered a new problem where userID 112112 added 110110 as a friend. 我遇到了一个新问题,用户ID 112112将110110添加为朋友。 because of this 112112 is in the userID column and 110110 is in the contactID column (contacts table). 因此112112在userID列中,而110110在contactID列(联系人表)中。 this shouldnt be a problem as it still shows they are contacts. 这不应该是一个问题,因为它仍然表明他们是联系人。 however I have tried to modify my query to also give me the name for the userID 112112. can someone please help me with this? 但是,我尝试修改查询以也为我提供用户ID 112112的名称。有人可以帮助我吗?

name, surname and ID 姓名,姓氏和身份证

Assuming by ID you mean contactID, otherwise additional join should be included to fetch data from Contacts. 按ID假设您的意思是contactID,否则应包括其他联接以从Contacts中获取数据。

select u.Firstname, u.Surname, uc.contactID from User u 
inner join UserContact uc on u.userID = uc.userID;

More on joins 有关联接的更多信息

To get all the users - 为了获得所有用户-

select Firstname, Surname, u.contactID from userdata u inner join usercontacts uc 
on u.userID = uc.userID order by Firstname, Surname, u.userID 

To get online users - 获取在线用户-

select Firstname, Surname, u.contactID from userdata u inner join usercontacts uc 
on u.userID = uc.userID where status = 'Online' order by Firstname, Surname, u.userID 

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

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