开发者

How can I find matches in two SQL tables?

I have two tables, UsersSample and UsersSearching. UsersMain is a table of the majority of available users. UsersSearching is a table of any users who have searched on the site.

I am trying to determine if a user from USersSample has searched (and appears in the UsersSearch开发者_运维技巧ing table). But I'm having difficulty even beginning this SQL query. Can anyone advise and point me in the right direction?


SELECT
    us.*
FROM UsersSample us
INNER JOIN UsersSearching uss ON uss.UserId = us.UserId

this will result in a list of users that exist in BOTH tables.


You can use a LEFT OUTER JOIN to determine which users have records in the UserSearching table:

select distinct u.UserID, us.UserID as HasSearchedUserID
from User u
left outer join UserSearching us on u.UserID = us.UserID

If HasSearchedUserID is NULL, then that user has not searched,


First, you need to define what fields are used to match records in the two tables. For example, if there's a common UserID field in the two tables, your query could use one of these two forms:

SELECT * FROM UsersSample WHERE UserID IN (SELECT UserID FROM UsersSearching)

SELECT UsersSample.* FROM UsersSample INNER JOIN UsersSearching
   ON UsersSample.UserID = UsersSearching.UserID

SELECT * FROM UsersSample WHERE EXISTS 
   (SELECT * FROM UsersSearching WHERE UsersSearching.UserID = UsersSample.UserID)

If you need to use two or more columns to determine matches, you can use modified versions of the second and third options shown above.


UsersSearching is a table of any users who have searched on the site.

I am trying to determine if a user from USersSample has searched (and appears in the UsersSearching table).

So, I need clarification on your problem, you want to know if UserSample are being added to UserSerching when they have searched or you know being added and just want to see what users are in both USersSample AND UsersSearching? If 1st, that would be more a testing thing than a SQL Query for 2nd.

SELECT UserID
FROM USersSample JOIN UserSearching
    ON USersSample.UserID = UserSearching.UserID

SELECT is the column(s) you want UserID FROM you want to look at 2 different tables so you need to JOIN them and with a JOIN you need ON as pointer ON [table.column] so on USerSample.UserID and show results that are equal = to UserSearching.UserID

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜