Join two select queries in mysql

pse :

I am trying to join two select queries but i am unable to get any results. Please help me to join these queries.

First Query ==>

SELECT *,all_posts.id as lid,all_posts.image as lpimage, users.image as uimage,all_posts.post_for_id as typ_id FROM all_posts LEFT JOIN users on all_posts.user_id = users.id WHERE all_posts.parent_id = 0 order by lid desc limit 5;

This query returns all posts irrespective of "access" field => Public, Friends, NULL

Click here for the result

Sample Data ===== all_posts table

id    user_id     image      post_type      post_date        access
==    ========   =====      =======    =========              =====
4526     1663   undefined    image     2020-03-07 06:47:04    Public
4523     196    undefined    image     2020-03-07 06:47:04    Friends

Users table=>

id    name    
==    ======== 
1663   test1  
196    test2   
1966   test3

Friends Table -

id    from_id      to_id    add_date    
==    ========      =====       =======
316    196          1966       2019-10-15

Second query ==>

SELECT count(*) as isfriend from friend where (from_id=:from_id and to_id=:user_id) or (from_id=:user_id and to_id=:from_id)

This query returns 1 or 0 based on of the current user is a friend of the other user(In my case i want to check with the each user_id from the above result of Query1). Click here for the result My query ==>

 SELECT *,all_posts.id as lid,all_posts.image as lpimage, users.image as uimage,all_posts.post_for_id as typ_id FROM all_posts LEFT JOIN users on all_posts.user_id = users.id WHERE user.id = 1(SELECT count(*) as isfriend from friend where (from_id=:from_id and to_id=:user_id) or (from_id=:user_id and to_id=:from_id)) all_posts.parent_id = 0 order by lid desc limit 5;

I want a query where i can get all the Public posts from first query also the posts which has the "access" as "Friends" AND user_id is a friend of the current user. That means i have to join these two queries to get this. Please help me to get this right. Thankyou.

loverwien :

I think this could be the right direction:

SELECT *,all_posts.id as lid,all_posts.image as lpimage, users.image as uimage,all_posts.post_for_id as typ_id FROM all_posts LEFT JOIN users on all_posts.user_id = users.id WHERE all_posts.parent_id = 0 AND (all_posts.access = 'Public' OR (all_posts.access = 'Friends' AND 0 < (SELECT count(*) as isfriend from friend where (from_id=all_posts.user_id and to_id=users.id) or (from_id=users.id and to_id=all_posts.user_id))) ORDER BY lid DESC LIMIt 5;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217427&siteId=1