有2张表,相册photo和日志blog(2张表没有联系,表字段不一样),2个表中都有createtime字段,现在需求是按照createtime排序分页(2张表中的所有数据),sql语句应该怎么写?

解决方案 »

  1.   

    表结构不重要吧,因为这2张表都没有任何联系的,只是有个共同的创建时间字段createtime,现在是怎么按照这个时间排序,你可以弄个最简单的,blog表中有blogid、createtime,photo表中有photoid,createtime
      

  2.   

    查询是我临时写的, MySQL的语法不太熟悉。但是思路是把两张表的数据放到一张临时表中,对这张表进行排序。
    create temporary table mytemptable ( 
    select blogid id,creatime from tblblog 
    union all 
    select photoid id, creatime from tblphoto
    );select id, createtime from mytemptable order by createtime 类似这样行不行?
      

  3.   

     (不要高估你的汉语表达能力或者我的汉语理解能力)
       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://bbs.csdn.net/topics/320211382
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。
      

  4.   


    --
    -- 表的结构 `blog`
    --CREATE TABLE IF NOT EXISTS `blog` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `content` varchar(255) NOT NULL,
      `img` varchar(255) NOT NULL,
      `createtime` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;--
    -- 转存表中的数据 `blog`
    --INSERT INTO `blog` (`id`, `title`, `content`, `img`, `createtime`) VALUES
    (1, '博文1', '内容1', '/data/1.jpg', 135),
    (2, '博文2', '内容2', '/data/2.jpg', 139);
    -- ----------------------------------------------------------
    -- 表的结构 `photo`
    --CREATE TABLE IF NOT EXISTS `photo` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `img` varchar(255) NOT NULL,
      `createtime` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;--
    -- 转存表中的数据 `photo`
    --INSERT INTO `photo` (`id`, `title`, `img`, `createtime`) VALUES
    (1, '图片1', '/data/3.jpg', 137);-- ----------------------------------------------------------
    -- 实现效果
    --id     type       title        img        createtime
    1     'blog'     '博文1'   '/data/1.jpg'     135
    1     'photo'    '图片1'   '/data/3.jpg'     137   
    2     'blog'     '博文2'   '/data/2.jpg'     139因为有个页面需要混合展示日志和相册(瀑布流或者分页),按照时间排序,这2个表是没有任何联系的,能用sql语句实现么,现在我的做法是blog和photo先读取数据后(limit)在程序中把2个结果合并后按照createtime排序,不过这样做其实没有真正达到按照createtime排序
      

  5.   

    1. 先将两个表合并成一个view. (在一个存储过程中使用临时表也可行)
    2. 在view上面进行select操作.create view v_mixblogphoto
    as
    select id,'blog' type,title,img,createtime from blog
    union all
    select id,'photo' type,title,img,createtime from photo
    SELECT* 
    FROM`v_mixblogphoto` 
    ORDERBY createtime
    LIMIT 0 , 30
      

  6.   

    或者一条SQL也行SELECT id, 
    TYPE , img, createtime
    FROM (
    SELECT id,'blog'
    TYPE , img, createtime
    FROM blog
    UNION ALL SELECT id,'photo'
    TYPE , img, createtime
    FROM photo
    )tmp
    ORDER BY createtime
    LIMIT 0 , 30