我有一個表(My)SQL查詢的結果。在這張表中,我有創建時間戳和用戶評論創建時間戳。訣竅是,並非所有的帖子都有評論(所以一些是NULL)。如何選擇MySQL中每行的兩個元素的最大值
我想根據帖子或用戶評論的最近創建時間排序。
我如何獲得每行的max(post_creation, comment_creation)
並訂購它們(訂購DESC
)?
感謝您的貢獻。
我有一個表(My)SQL查詢的結果。在這張表中,我有創建時間戳和用戶評論創建時間戳。訣竅是,並非所有的帖子都有評論(所以一些是NULL)。如何選擇MySQL中每行的兩個元素的最大值
我想根據帖子或用戶評論的最近創建時間排序。
我如何獲得每行的max(post_creation, comment_creation)
並訂購它們(訂購DESC
)?
感謝您的貢獻。
根據你前面的問題,請嘗試:
SELECT p.id AS post_id,
p.author_id AS post_author_id,
p.created_date AS post_created,
c.author_id AS comment_author_id,
c.created_date AS comment_created,
p.title,
c.content,
coalesce(c.created_date,p.created_date) AS sort_date
FROM Posts p
LEFT JOIN Comments c ON p.id = c.post_id
WHERE p.author_id = $userId
UNION ALL
SELECT p.id AS post_id,
p.author_id AS post_author_id,
p.created_date AS post_created,
c.author_id AS comment_author_id,
c.created_date AS comment_created,
p.title,
c.content,
c.created_date AS sort_date
FROM Posts p
RIGHT JOIN Comments c ON p.id = c.post_id
WHERE c.author_id = $userId
ORDER BY sort_date
非常感謝您的幫助Mark。你的代碼在我的情況下成功運作。對於那些想要了解更多信息,請參閱我以前的問題:http://stackoverflow.com/questions/9530760/get-user-posts-and-or-comments-in-a-sharing-blog-using-sql – htaidirt 2012-03-02 21:53:07
@哈西努斯:也許你不知道你被允許(並極力鼓勵)[正式接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work「How do接受答案的工作?「)答案最能幫助你解決問題,每個問題一個答案。當你在SO上獲得更多聲望時,你還可以[upvote answers and questions](http://stackoverflow.com/privileges/vote-up「投票問題和答案」)。 – 2012-03-05 07:35:19
鑑於你的表看起來像這樣...
CREATE TABLE `yourtable` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`post_creation` timestamp NULL DEFAULT NULL,
`comment_creation` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
...的SELECT
-query可以做這樣的:
SELECT IF(comment_creation > post_creation,
comment_creation,
post_creation) AS sortorder,
id
FROM yourtable
ORDER BY sortorder DESC;
你的答案似乎很有趣。但它涉及兩個值之間的比較:Max(A,B)。兩個以上的值如何:Max(A1,A2,...,An)?有沒有(My)SQL函數? – htaidirt 2012-03-02 21:56:52
請提供更多詳細信息,表格如何。 MAX()是一個聚合函數,用於比較不同的行,而不是不同的字段。 – Bjoern 2012-03-03 10:19:27
讓我們考慮一個有N個科目(數學,生物學......)的學者課程。每一行(在我的數據庫中)都是一個學生,每一列都是一個主題。相比之下,我的數據庫中的每個字段都包含某個學科的學生分數。我怎樣才能得到每個學生最好的分數和相應的科目? – htaidirt 2012-03-03 19:29:24
我假設'comment_creation'(如果存在的話)總是大於'post_creation'? – 2012-03-02 11:03:32
確實。但是我們首先要檢查comment_creation是否存在。 – htaidirt 2012-03-02 11:20:53