1

I have a table with feed for our system

it's look like this:

id | owner_id | user_id | feed_type_id | object_id | created_at | updated_at

feed_type_id - represent type of object that is stored in different table (article or job_post)

object_id is the object ID itself, but I don't have a clue if this object is still active. So I have get all active id for different type of object, but when I am trying to build query with IF statement something like this

SELECT * 
FROM feeds 
WHERE "owner_id" in (2, 4, 1356) 
  AND object_id IN ( IF `feed_type_id` = 1 THEN (2,3,23,33) ELSE (4,5,77,33) end if)

it's not working.

Can someone give me an idea how to do this?

0

2 Answers 2

3

IF statements are not part of the SQL language, but part of the procedural language. As such, you can't use them directly in queries.

The query you're looking for is something like this:

SELECT * 
FROM feeds 
WHERE 
    "owner_id" in (2, 4, 1356) AND 
    (
        ("feed_type_id" = 1 AND "object_id" IN (2, 3, 23, 33)) OR
        ("feed_type_id" != 1 AND "object_id" IN (4, 5, 77, 33))
    )
Sign up to request clarification or add additional context in comments.

Comments

3

You can use CASE expression like this

SELECT * 
FROM feeds 
WHERE "owner_id" IN (2, 4, 1356) 
AND object_id    IN (CASE 
                         WHEN "feed_type_id" = 1 THEN (2,3,23,33) 
                         ELSE (4,5,77,33) 
                     END)

1 Comment

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.