开发者

Adding extra field to sql query

I have a query i've written for a private message system but i would like to add an extar field in the query but not sure how to do it.

At the moment it gets the username of the sender but not the recipient but it does however get both ids of sender/recipient.

How do i add an extra field in my query to get the username of the recpient? I thought about a nested select.

Here is开发者_如何学Go my current query

SELECT p.*, u.username as sender, DATE_FORMAT(u.signup_date, '%b %Y') as joindate, m.avatar FROM privatemsgrec p INNER JOIN users u ON p.senderid=u.userid INNER JOIN misc m ON m.userid=u.userid WHERE p.messageid='1' LIMIT 1

and here is the table structures

CREATE TABLE IF NOT EXISTS `misc` (
  `miscid` int(4) NOT NULL auto_increment,
  `userid` int(4) NOT NULL default '0',
  `profpic` varchar(100) NOT NULL default '',
  `avatar` varchar(100) NOT NULL default '',
  `signature` text NOT NULL,
  `alerts` enum('y','n') NOT NULL default 'y',
  PRIMARY KEY  (`miscid`)
)

CREATE TABLE IF NOT EXISTS `privatemsgsent` (
  `messageid` int(10) NOT NULL auto_increment,
  `senderid` int(4) NOT NULL default '0',
  `recipientid` int(4) NOT NULL default '0',
  `subject` varchar(255) NOT NULL default '',
  `message` text NOT NULL,
  `datesent` date NOT NULL default '0000-00-00',
  PRIMARY KEY  (`messageid`)
)

CREATE TABLE IF NOT EXISTS `users` (
  `userid` int(25) NOT NULL auto_increment,
  `first_name` varchar(25) NOT NULL default '',
  `email` varchar(255) NOT NULL default '',
  `username` varchar(25) NOT NULL default '',
  `password` varchar(32) NOT NULL default '',
  `salt` char(3) NOT NULL default '',
  `sex` varchar(6) NOT NULL default '',
  `user_level` enum('0','1','2','3') NOT NULL default '0',
  `signup_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `last_login` datetime NOT NULL default '0000-00-00 00:00:00',
  `activated` enum('0','1') NOT NULL default '0',
  PRIMARY KEY  (`userid`)
)


SELECT p.*, 
    us.username as sender, ur.username as recipient, 
    DATE_FORMAT(u.signup_date, '%b %Y') as joindate, m.avatar
FROM privatemsgrec p 
INNER JOIN users us ON p.senderid = us.userid 
INNER JOIN users ur ON p.recipientid = ur.userid 
INNER JOIN misc m ON m.userid = u.userid 
WHERE p.messageid = '1' 
LIMIT 1 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜