【发布时间】:2011-06-01 22:15:25
【问题描述】:
所以我有 2 个表,它们没有任何共同的列,我想按它们的日期列存储它们
所以 table1 是这样的:
表1
- 身份证
- post_id
- post_date
表2
- 身份证
- 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`, `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
【问题讨论】:
-
描述我不知道如何识别哪个项目(帖子或评论)
-
所以可以说我的 table1 有一些记录,但 table2 仍然为空......我怎么知道要显示哪些数据?table1 或 table2 的?因为我在两个表上都有不同的列
-
您的主题说您想按日期加入,但您的代码按 id 加入。这对我来说毫无意义。完全没有。你到底想完成什么?
-
因为我使用 ORDER BY post_date DESC,comment_date DESC 不是加入 2 个表并按日期显示 DESC 吗?我试图按日期显示这 2 个表 DESC 中的所有记录
-
cmet 与帖子无关吗?