2

I have two tables resource (id, name, ...) and user_favorites(user_id, resource_id) which has foreign key resource_id from the resource table.

I have a situation where I need to check if resource table has any records to user_favorites table for a particular user_id in user_favorites table, and put a flag true or false accordingly.

This is the last query I could come up with

SELECT distinct resources.*,
       (CASE WHEN user_favorites.user_id='1' then 'TRUE' ELSE 'FALSE' END) as favorite,
       user_favorites.user_id
FROM resources LEFT JOIN
     user_favorites
     ON resources.id = user_favorites.resource_id

However, what I want to be able to keep the resources. With the current query, it records false when there are records for other user ids also.

What is the best way to approach this problem?

7
  • 1
    Syntax error. Missing comma after resources.*. Commented Aug 1, 2018 at 10:58
  • one way is this: you'd need a WHERE clause to restrict to the desired user ID. In the CASE you can then just check whether favourites.user_id is null or not. Haven't tested that obviously but I'm fairly sure it would work. Commented Aug 1, 2018 at 10:59
  • @jarlh Corrected. Thanks Commented Aug 1, 2018 at 11:00
  • @ADyson I want to be able to show all resource records without restricting the ID, but be able to put up a flag TRUE or FALSE based on whether there are any records on the user favorites table for that particular ID Commented Aug 1, 2018 at 11:01
  • Add example data and expected results as text formatted data table we are geussing here.. Place the SQL example data on sqlfiddle.com or db-fiddle.com Commented Aug 1, 2018 at 11:05

2 Answers 2

2

You can use expression logic in the select. In MySQL, you don't even need case:

SELECT r.*, 1 as user_id,
       (EXISTS (SELECT 1
                FROM user_favorites uf
                WHERE r.id = ur.resource_id AND
                      ur.user_id = 1
               )
       ) as flag
FROM resources r ;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. I will accept the answer in 5 minutes
0

Use this

SELECT 
r.*
, IFNULL(ur.totalUser, 0) AS totalUser
FROM `resource` r
LEFT JOIN 
(
    SELECT 
    resource_id
    , COUNT(user_id) AS totalUser
    FROM `user_favourites` 
    GROUP BY resource_id
) AS ur ON ur.resource_id = r.`id` 

Comments

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.