MYSQL选择子查询IF存在

时间:2015-08-02 08:15:18

标签: mysql sql select mysqli subquery

我有3个表......用户,更新和颠簸。

我想让用户以最近的顺序返回给api请求的Feed更新,并显示所有需要的数据以显示Feed中的每个状态。 我还需要包括更新是否已经过了"碰撞"用户是否发出api请求(碰撞=喜欢facebook上的状态)

简而言之,这就是我想要做的事情,即使这个查询的if count区域没有接近正确的语法:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

添加LEFT JOIN以将所有结果连接到BUMPS,如果值不存在则返回NULL

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