0

I have table users and another table premium_users in which I hold the userid and the date when he bought premium membership.

How can I use mysql join , so that in a single query I can select all the columns from the table users and also know for each premium user the date he joined on.

USERS:

ID USERNAME
1  JOHN
2  BILL
3  JOE
4  KENNY

PREMIUM USERS:

ID USERID DATE
1  2      20/05/2010
2  4      21/06/2011

And the final table (the one that will be returned my the query) should look like this:

ID USERNAME DATE
1  JOHN
2  BILL     20/05/2010
3  JOE
4  KENNY    21/06/2011

Is it ok for some rows to have the DATE value empty? How can I check if that value is empty? $row['date']=='' ?

EDIT: This was only an example, but the users table has much more columns, how can I select all from users and only date from premium_users without writing all the columns?

5 Answers 5

1
select u.*, pu.DATE
from USERS u LEFT OUTER JOIN PREMIUM_USERS pu on
  u.ID = pu.USERID

You can check if a row is empty with:

if (!$row['DATE'])
{
   ... 
}
Sign up to request clarification or add additional context in comments.

Comments

0
select USERS.ID, USERS.USERNAME, PREMIUM_USERS.DATE
from USERS
join PREMIUM_USERS on USERS.ID = PREMIUM_USERS.ID
order by USERS.ID

Comments

0

This is mssql syntax, but it should be pretty similar...

select *
from users u
left join premiumUsers p
on u.id = p.id
order by u.id asc

2 Comments

It's the same syntax in MySQL.
@Johan - thanks for the clarification, I figured if it wasn't exactly the same it was very close
0
SELECT A.*, B.DATE
FROM USERS A
LEFT JOIN PREMIUIM_USERS B on A.ID=B.USERID

EDITED

Comments

0

It might be easier to have it all in one table. You can have nullable fields for isPremium(t/f) and premiumDate. you actually dont even need the isPremium field. just premiumDate if its null they are not premium and if it has value they are premium user and you have the date they joined.

4 Comments

I don't actually have an "isPremium" column. And I do this because in some queries I only need to select premium users, so it's better to do a query for only 40-50 users instead of 10.000
well you can always create a view for premium users. basicly select * from users where date is not null.
Yeah, but if I have 1.000.000 users and I do that select it would be very slow. If I have a separate premium table, when I want to see the premium users I only do a select from the users that ARE premium (less then 10% of the users table)
your gonna be doing a query on the users table regardless to get usernames. doing the it other way in certain situations you will have to make multiple queries. my was it should be one all the time. plus its simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.