SQL选择加入

时间:2014-06-22 14:02:31

标签: mysql sql select join

大家好我有桌面用户:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(30) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` varchar(50) NOT NULL,
  `firstname` varchar(20) NOT NULL,
  `lastname` varchar(20) NOT NULL,
  `birthdate` date DEFAULT NULL,
  `role` varchar(10) NOT NULL,
  `description` text,
  `fotopath` varchar(50) DEFAULT NULL,
  `city` varchar(20) NOT NULL,
  `street` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

和表private_message:

CREATE TABLE IF NOT EXISTS `private_message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_from` int(11) NOT NULL,
  `user_to` int(11) NOT NULL,
  `reply_id` int(11) NOT NULL,
  `message` varchar(400) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `readed` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_from` (`user_from`),
  KEY `user_to` (`user_to`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

ALTER TABLE `private_message`
  ADD CONSTRAINT `private_message_ibfk_1` FOREIGN KEY (`user_from`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `private_message_ibfk_2` FOREIGN KEY (`user_to`) REFERENCES `users` (`id`) ON DELETE CASCADE;

我想选择(user_from,user_to,message,from_username,to_username,readed,date)
我试过这个:

SELECT P.user_from,P.user_to,P.message,P.readed,P.date,U.username as from_username,D.username as to_username 
FROM private_message as P JOIN users as U ON(P.user_from=U.id) JOIN users as D ON(P.user_to=D.id) 
GROUP BY to_username,from_username

它给了我

user_from|user_to|message|from_username|to_username|readed|date  
    1    |   2   |  asdf |   Admin     |   Baski   |   0  | 2014-06-22 12:00:16  
    2    |   1   |  asdf |   Baski     |   Admin   |   0  | 2014-06-22 12:02:16  
    3    |   1   |  asdf |   Smrdis    |   Admin   |   0  | 2014-06-22 12:02:16  

我需要这样的表格:

user_from|user_to|message|from_username|to_username|readed|date  
    2    |   1   |  asdf |   Baski     |   Admin   |   0  | 2014-06-22 12:02:16  
    3    |   1   |  asdf |   Smrdis    |   Admin   |   0  | 2014-06-22 12:12:16  

当我选择时,我只知道我的user_id。我需要选择发送给用户或由用户发送的所有消息,并按第二人的ID(可以是发件人或接收者)对其进行分组。我不能简单地通过user_to或user_from对其进行分组,因为您只能发送消息并且不会得到响应。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

你可以添加这行WHERE。

WHERE U.id = ...
GROUP BY to_username,from_username