Reputation: 2434
I am struggling to get me head round the MySQL Join function.
Here is two tables I have:
User table:
admin_id username
*1 peter93
2 stackoverflowrocks
3 user3*
Admin details table:
admin_username description image
pedro93 [text] [image_url]
stackoverflowrocks [text] [image_url]
user3 [text] [image_url]
I know usualy to link two databases together you would use ID numbers, but in this case I want to join the two tables where admin_username = username.
Can anyone help me please? It is for a PHP script if that helps.
Thanks in advance! Peter
Upvotes: 1
Views: 103
Reputation: 9933
You can join on pretty much any field but you may wish to keep in mind datatype mismatching, indexing etc
All users
SELECT u.*, a.*
FROM users AS u
LEFT JOIN admin AS a
ON u.username = a.username
All users that are admin
SELECT u.*, a.*
FROM users AS u
INNER JOIN admin AS a
ON u.username = a.username
All admin
SELECT u.*, a.*
FROM users AS u
RIGHT JOIN admin AS a
ON u.username = a.username
Upvotes: 1
Reputation: 3412
joining by a string column is the same as joining by Id
select * from admin_table
inner join admin_details on admin_table.username = admin_details.admin_username
But make sure you have and index for the username columns, or else your queries will go slow when you have lots of records
Upvotes: 1
Reputation: 51494
So that's fine. You can join on anything you like.
select *
from user
inner join admin
on user.username=admin.admin_username
Upvotes: 7