2

I have two tables:

| USER |
| _id  | - int id PK
| id   | - String id
| name |

| SUBSCRIBE |
|   user    |
| subscribe |

and I want to extract this data:

| _id | id | name | subscribe

Simple example

| USER |
|  1   | 10212551 | Mike
|  2   | 21022145 | Nick

| SUBSCRIBE |
|    1      |     2


get_info($user, $sub );

| EXPECTED RESULT |
|     $user       |  id  |  name  |  0 or 1 (false or true, if $sub has subscribed to $user)

My best try was with count():

SELECT u._id,u.id,u.name,u.email,u.country,count(s.subscribe) AS subscribe 
FROM user u,subscribe s 
WHERE u._id='$user' AND s.subscribe='$user' AND s.user='$sub'

But this works only if there's any record in subscribe table. So for

get_info(2,1)

it will give right result but for:

get_info(1,2)

there's nothing :/

Can somebody please help me with this ?

1 Answer 1

1

Use left join in order to return user even if he has not subscribed and use case to check for subscribed

select u._id,u.id,u.name,u.email,u.country,
case when s.subscribe is not null then 1 else 0 end as subscribe 
from user u 
left join subscribe s on (u._id = s.user and s.subscribe ='$sub')
where u._id='$user' 

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

@MichalHeneš yup there was a typo missing end for case statement try it now
That code gives me always subscribe 0 even if there's a record
@MichalHeneš see my updated answer with sample demo
Yay, yes, your code works, but I must retype u._id = s.user and s.subscribe ='$sub' with u._id = s.subscribe and s.user ='$sub' thanks, my bad for not explained it properly :) ty

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.