php加入2个表日期问题

时间:2011-05-30 12:06:46

标签: mysql join

所以我有2个表没有任何共同的列,我想按日期列存储它们

所以table1就像:

表1

  • ID
  • POST_ID
  • POST_DATE

表2

  • ID
  • COMMENT_ID
  • COMMENT_DATE

我要展示的是来自table1,table2的所有内容,并按日期排序

我试过像

这样的东西
SELECT * FROM table1 INNER JOIN table2 ORDER BY post_date DESC, comment_date DESC

问题是我不知道如何识别我在while(row = 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`, `col1` AS `userid`, `col2` AS `cat`, `col3` AS `item_id`, NULL AS `title`, etc... , `date` AS `date` FROM `table2`
            ) AS tb
            ORDER BY `date` DESC

3 个答案:

答案 0 :(得分:3)

尝试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`, `id`, `comment_id` AS `table_id`, `comment_date` AS `date` FROM `table2`)
)
ORDER BY `date` DESC

那需要测试,不确定是否允许。

答案 1 :(得分:1)

如果要将帖子链接到评论,则必须重新设计数据库。

鉴于这些表格

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'";
....

在您当前的设计中,无法可靠地加入它们,因为两者之间没有任何关系。

答案 2 :(得分:0)

                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`, `col1` AS `userid`, `col2` AS `cat`, `col3` AS `item_id`, NULL AS `title`, etc... , `date` AS `date` FROM `table2`
        ) AS tb
        ORDER BY `date` DESC