如果找到则查询从表中检查详细信息然后是否则NO

时间:2013-05-16 06:49:29

标签: mysql

以下是我的查询。这是正常工作的问题是,从类似的表我无法检查特定用户是否喜欢元素。如果有人喜欢表示是,如果不喜欢则显示否。

SELECT
      u_m.*,concat(usr.fname,' ',usr.lname) as NAME,
      u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,
      u_m_u.author,u_m_u.adddate

FROM user_message_users AS u_m_u
      LEFT JOIN user_messages AS u_m
        ON u_m.messageid = u_m_u.messageid
       LEFT JOIN smsusers AS usr
        ON u_m_u.sent_by=usr.id
       LEFT JOIN likes 
        ON u_m.messageid=likes.element_id 
        and
        likes.liked_by='1'
        group by u_m_u.messageid,u_m_u.sent_to
       ORDER BY u_m_u.adddate desc;

喜欢表格是

create table likes(
element_id varchar(100),
element_type varchar(100),
liked_by varchar(100), 
foreign key(liked_by) references smsusers(id)
 ON DELETE CASCADE ON UPDATE CASCADE,
adddate timestamp DEFAULT CURRENT_TIMESTAMP,
primary key(element_id,liked_by));

我的查询link

2 个答案:

答案 0 :(得分:0)

SELECT
      u_m.*,concat(usr.fname,' ',usr.lname) as NAME,
      u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,
      u_m_u.author,u_m_u.adddate,
      if (likes.element_id IS NULL, "No", "Yes") Likes

答案 1 :(得分:0)

尝试此查询: -

SELECT
      u_m.*,concat(usr.fname,' ',usr.lname) as NAME,
      u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,
      u_m_u.author,u_m_u.adddate,if(likes.liked_by is null,'No','Yes')
as likees

FROM user_message_users AS u_m_u
      LEFT JOIN user_messages AS u_m
        ON u_m.messageid = u_m_u.messageid
       LEFT JOIN smsusers AS usr
        ON u_m_u.sent_by=usr.id
       LEFT JOIN likes 
        ON u_m.messageid=likes.element_id 
and
likes.liked_by='1'
group by u_m_u.messageid,u_m_u.sent_to
ORDER BY u_m_u.adddate desc;

尝试SQLFiddle