无法从表中获取数据

时间:2013-05-06 11:02:25

标签: mysql sql-server

我有下表

create table smsusers(
  id varchar(60),
  password varchar(50) not null,
  fname varchar(30) not null,
  lname varchar(30),
  mailid varchar(50) not null,
  gender varchar(10) not null,
  primary key(id)
);

create table profile_pic(
  pic_id varchar(200),
  profile_pic_path varchar(1000),
  small_pic_path varchar(1000),
  adddate varchar(100),
  userid varchar(60),
  foreign key(userid) references smsusers(id)
      ON DELETE CASCADE ON UPDATE CASCADE,
  primary key(pic_id)
);

create table user_messages(
messageid varchar(200),
message varchar(1000),
visibility varchar(100),
primary key(messageid)
);


create table user_message_users(
messageid varchar(200),
sent_to varchar(60),
sent_by varchar(60),
shared_of varchar(60),
author varchar(60),
adddate timestamp DEFAULT CURRENT_TIMESTAMP,
primary key(messageid,sent_by),
foreign key(sent_to) references 
smsusers(id) ON DELETE CASCADE ON UPDATE CASCADE,
foreign key(messageid) references 
user_messages(messageid) ON DELETE CASCADE ON UPDATE CASCADE,
foreign key(sent_by) references smsusers(id),
foreign key(shared_of) references smsusers(id),
foreign key(author) references smsusers(id)
);

我在这里讨论来自上表的数据 因为我正在写查询

SELECT
      u_m.messageid,u_m.message,u_m.visibility,
      u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,
      u_m_u.author,u_m_u.adddate,
      concat(usr.fname,' ',usr.lname) AS sender_name,
      p_p.small_pic_path

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 profile_pic AS p_p
        ON u_m_u.sent_by=p_p.userid

group by u_m_u.messageid
ORDER BY u_m_u.adddate desc;

此查询在此处正常运行我获取了详细信息和SENT_BY's名称以及small_pic_path 现在,我想在此查询中获取SENT_TO's名称和small_pic_path

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
      u_m.messageid,u_m.message,u_m.visibility,
      u_m_u.sent_to,u_m_u.sent_by,u_m_u.shared_of,
      u_m_u.author,u_m_u.adddate,
      concat(usr.fname,' ',usr.lname) AS sender_name,
      p_p.small_pic_path
      concat(send_to_usr.fname,' ',send_to_usr.lname) AS send_to_name,
      send_to_p_p.small_pic_path send_to_pic

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 profile_pic AS p_p
        ON u_m_u.sent_by=p_p.userid
       LEFT JOIN smsusers AS send_to_usr
        ON u_m_u.sent_to=send_to_usr.id
       LEFT JOIN profile_pic AS send_to_p_p
        ON u_m_u.sent_to=send_to_p_p.userid 

group by u_m_u.messageid
ORDER BY u_m_u.adddate desc;