社交网站数据库的mySql存储过程

时间:2013-08-22 07:37:57

标签: mysql stored-procedures view mysqli

我想为以下数据库架构创建存储过程

具有id和所有其他用户详细信息的用户表,用户可以创建相册,他们将添加图片并邀请朋友喜欢和评论我想要显示最近五张专辑和喜欢的图片,对专辑照片的评论和计数分享该专辑的朋友

CREATE TABLE `albums` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `created` date NOT NULL DEFAULT '0000-00-00',
  PRIMARY KEY (`id`),
  KEY `UserAlbum` (`user_id`)
) 

CREATE TABLE `shared_albums` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `album_id` bigint(20) unsigned NOT NULL,
  `shared_user_id` int(11) unsigned NOT NULL,
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  KEY `UserSharedAlbum` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

CREATE TABLE `pictures` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `album_id` bigint(20) unsigned NOT NULL,
  `caption` text,
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `UserPicture` (`user_id`),
  KEY `PicturesAlbum` (`album_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

然后有表格保存图片评论和图片喜欢。我想创建一个mySql存储过程来获取所有这些表的组合信息

最后我想输出json数据为

{
  "meta": [
        {
          "total_albums" : 25,
        }
      ]

  "albums": [
      {
        "id" : 205488
          "title": "album title",
          "cover_image": "http://images.example.com/4133bc0c08b211e38b1d22000ae91391_7.jpg",
          "images":[
              {
                "http://images.example.com/4133bc0c08b2134wtr58b1d22000ae91391_6.jpg"
                "http://images.example.com/143rtbc0c08b2134wtr58b1d22000ae91391_7.jpg"
                "http://images.example.com/5633bc0c08b2134wtr58b1d22000778g91_6.jpg"
                "http://images.example.com/5633bc0c08b2134wtr58b1d22000778g91_6.jpg"
              }
             ],
          "friends": 27,
          "images": 154,
          "comments": 75,
          "likes" : 19,
          "last_update" => "just now"
      },

......最后五张专辑

我尝试了什么

CREATE PROCEDURE get_user_albums(user_id INT)
BEGIN
DECLARE album_count INT;
DECLARE friends_count INT;
DECLARE images_count INT;
DECLARE comments_count INT;
DECLARE likes_count INT;

SELECT COUNT(`id`.`albums`) as album_count FROM `albums` WHERE `albums`.`user_id` = user_id;


END;

我可以获得每张专辑的喜欢,评论等数量,如何在存储过程中使用数组。

0 个答案:

没有答案