微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php通过日期问题加入2个表

如何解决php通过日期问题加入2个表

| 所以我有2个没有任何共同点的表,我想按它们的日期列来存储它们 所以table1像这样: 表格1 ID post_id 发布日期 表2 ID comment_id comment_date 我要显示的是table1,table2中的所有内容,并按日期排序 我尝试过类似的东西
SELECT * FROM table1 INNER JOIN table2 ORDER BY post_date DESC,comment_date DESC
问题是我不知道如何识别在while(rows = MysqL_fetch_assoc())内部使用的项目(发布或评论),因为我具有不同的列名。 解决方案是:
                SELECT * FROM (
                SELECT 1 AS `table`,`col1` AS `userid`,`col2` AS `cat`,`col3` AS `item_id`,`title` AS `title`,etc...,`date` AS `date` FROM `table1`
                UNION
                SELECT 2 AS `table`,NULL AS `title`,`date` AS `date` FROM `table2`
            ) AS tb
            ORDER BY `date` DESC
    

解决方法

        尝试
UNION
,并使用新的常量列指示正在输出的表,并使用
AS
使列名相同。 周围的
SELECT
可能使您可以一起订购。
SELECT * FROM (
    (SELECT 1 AS `table`,`id`,`post_id` AS `table_id`,`post_date` AS `date` FROM `table1`)
    UNION
    (SELECT 2 AS `table`,`comment_id` AS `table_id`,`comment_date` AS `date` FROM `table2`)
)
ORDER BY `date` DESC
那将需要测试,不确定是否允许。     ,        若要将帖子链接到评论,则必须重新设计数据库。 给定这些表
table1

    id
    post_id
    post_date

table2

    id
    comment_id
    comment_date
注释应该是属于帖子的注释,因此您需要更改表,以便其结构变为:
table post

    id         /*id of a post*/
    user_id    /*which user posted this*/
    post_date  /*when?*/
    post_text  /*the text inside the post*/

table comments

    id            /*id of a comment*/
    post_id       /*which post does this comment belong to*/
    user_id       /*who posted this*/
    comment_date  /*when*/
    comment_text  /*text of the comment*/
现在,您可以通过执行以下操作加入此操作:
$post_id = mysql_real_escape_string($_GET[\'post_id\']);

/*select all comments belonging to a post*/
$query = \"SELECT c.user_id,c.comment_date,c.comment_text FROM posts p
          INNER JOIN comments c ON (c.post_id = p.id)
          WHERE p.id = \'$post_id\'\";
....
在当前设计中,由于两者之间没有关系,因此无法可靠地连接它们。     ,        
                SELECT * FROM (
            SELECT 1 AS `table`,`col1` AS `userid`,`col2` AS `cat`,`col3` AS `item_id`,`title` AS `title`,etc...,`date` AS `date` FROM `table1`
            UNION
            SELECT 2 AS `table`,NULL AS `title`,`date` AS `date` FROM `table2`
        ) AS tb
        ORDER BY `date` DESC
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。