开发者

How to use inner join to get username from one table by the ID stored in another

I have the two tables below.

The table jobs will have a user id stored in the added_by field.

The table users will have the username stored along with an id.

I want to select the username by matching up the id in the added_by field, with the id in the users field.

Thanks for any help offered.

This is the jobs table

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
title   varchar(255)    NO      NULL    
description text    NO      NULL    
priority    int(1)  NO      1   
added_by    int(11) NO      NULL    
added_on    time    NO      NULL    
completed   int(3)  NO      0   
date_completed  timestamp   NO      0000-00-00 00:00:00 

This is the users field

id  int(11) NO  PRI NULL    auto_increment
username    varchar(30) NO  MUL NULL    
password    varchar开发者_Go百科(32) NO      NULL    
email   varchar(255)    NO      NULL    
level   int(1)  NO      NULL    


select j.title, u.username from jobs j left join users u on u.id=j.added_by


SELECT U.username
FROM users U
INNER JOIN jobs J on (J.added_by = U.id)


SELECT T1.*, T2.username FROM jobs AS T1 INNER JOIN users AS T2 ON T1.added_by=t2.id

Something like that should do the trick.


You'll have to specify what you want in the results table. The following will retreive only those usernames that have an ID in their table matching an 'added_by' field in the jobs table. The results will display only the username.

SELECT table_users.*,table_jobs.* FROM users AS table_users
     INNER JOIN ( SELECT added_by FROM jobs) AS  table_jobs
     ON table_users.id = table_jobs.added_by
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜