MYSQL Select Subquery IF exists

谁说我不能喝 提交于 2019-12-12 01:23:05

问题


I have 3 tables ....users, updates and bumps.

I want to return the user making the api request a feed updates in most recent order with all the needed data to display each of the statuses in the feed. I also need to include whether the update has been "bumped" by the user making the api request or not (bumped = liking a status on facebook)

In a nutshell this is what I am trying to do even though the if count area of this query is no where near correct syntax:

SELECT b.type,b.owner,b.update_img,b.ALBUM_ID,b.last_comment,a.uid, a.first_name, a.last_name, a.gender, a.thumb_img, b.msg_id, b.message, b.created,b.POST_PRIVACY,
(if count( SELECT  * FROM BUMPS WHERE  b.msg_id= BUMPS.MSG_ID_FK  AND BUMPS.UID_FK=$loggedin_uid)>0  THEN  1  ELSE  null)  as 'isBumpedBool'
FROM users AS a, updates AS b
WHERE b.uid_fk = a.uid
AND b.type<>'FRIEND_RELATIONSHIP'
AND b.created<$time
AND b.type<>'FAMILIAR_RELATIONSHIP'
AND a.college='$college'
AND b.POST_PRIVACY<>'4'
AND b.POST_PRIVACY<>'5'
AND b.created>=$tstamp
ORDER BY b.created DESC
LIMIT 100

Any ideas?


回答1:


Add a LEFT JOIN to get all those result JOINed to BUMPS and return NULLs if the values are not there

SELECT b.type,
       b.owner,
       b.update_img,
       b.ALBUM_ID,
       b.last_comment,
       a.uid,
       a.first_name,
       a.last_name,
       a.gender,
       a.thumb_img,
       b.msg_id,
       b.message,
       b.created,
       b.POST_PRIVACY,
       (CASE WHEN bm.MSG_ID_FK IS NOT NULL THEN 1 ELSE NULL END) AS 'isBumpedBool'
FROM users AS a JOIN
     updates AS b
ON b.uid_fk = a.uid
  AND b.type<>'FRIEND_RELATIONSHIP'
  AND b.created<$time
  AND b.type<>'FAMILIAR_RELATIONSHIP'
  AND a.college='$college'
  AND b.POST_PRIVACY<>'4'
  AND b.POST_PRIVACY<>'5'
  AND b.created>=$tstamp
LEFT JOIN BUMPS as bm 
ON b.msg_id= bm.MSG_ID_FK
             AND bm.UID_FK=$loggedin_uid
ORDER BY b.created DESC LIMIT 100


来源:https://stackoverflow.com/questions/31769884/mysql-select-subquery-if-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!