user967451
user967451

Reputation:

How to combine these 2 MySQL SELECT statements together?

On my users table there is a column called featured. If it has a value of 1 then the user is featured, if 0 then not featured.

On my homepage I want to display all users on my site. But I want the featured ones to show before the non featured ones.

Statement 1:

SELECT *
FROM `users`
JOIN `profiles` ON users.user_id = profiles.user_id
JOIN `geo` ON users.zip = geo.zip_code
JOIN `user_activity` ON users.user_id = user_activity.user_id
WHERE users.featured = '1'
ORDER BY users.user_id DESC
LIMIT ". ($page_num - 1) * $per_page .", ". $per_page;

Statement 2:

SELECT *
FROM `users`
JOIN `profiles` ON users.user_id = profiles.user_id
JOIN `geo` ON users.zip = geo.zip_code
JOIN `user_activity` ON users.user_id = user_activity.user_id
WHERE users.featured != '1'
ORDER BY users.user_id DESC
LIMIT ". ($page_num - 1) * $per_page .", ". $per_page;

Both statements are identical except the where clause. How to merge these 2 together so featured users show first and then non featured ones.

EDIT

I should have mentioned, I would like the result set to be returned as one collection.

Upvotes: 1

Views: 115

Answers (1)

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171579

SELECT *
FROM `users` u
JOIN `profiles` p ON u.user_id = p.user_id
JOIN `geo` g ON u.zip = g.zip_code
JOIN `user_activity` ua ON u.user_id = ua.user_id
ORDER BY u.featured DESC,
    u.user_id DESC
LIMIT ". ($page_num - 1) * $per_page .", ". $per_page;

Upvotes: 3

Related Questions