Resulting data on last thread_date

醉酒当歌 提交于 2019-12-13 11:07:04

问题


As I fixed the previous question thanks to the answer, I am sticking now in the part to retrieve a thread based on the last thread_date.

The code itself seems to be working fine, but it is only printing one result out instead of others.

The thread has a threads.cat_id which is linked to thesubsubcategory.extra_cat_id.

SELECT 
parent.subcat_id, 
parent.subcat_name, 
child.subsubcat_name, 
child.subcat_id, 
child.cat_id, 
kid.thread_name, 
kid.cat_id, 
kid.thread_date 
FROM 
subcategories parent  
JOIN subsubcategories child 
ON child.cat_id = parent.cat_id
 JOIN threads kid ON child.extra_cat_id = kid.cat_id 
WHERE thread_date = (SELECT MAX(thread_date) FROM threads)

What I am expecting is this:

 Category
    Subcategory       Latest thread
    Subcategory       Latest thread

What I am getting is this:

Category
  Subcategory       Latest thread  

SQL fiddle: http://sqlfiddle.com/#!9/52e27/2

Any solutions to it?

Thanks!


回答1:


If my guess is right, you want to edit the where clause to show more based on last date as your threaddate is a datetime, you have to convert it to a date format before comparing it.

    SELECT parent.subcat_id,
        parent.subcat_name,
        child.subsubcat_name,
        child.subcat_id,
        child.cat_id,
        kid.thread_name,
        kid.cat_id,
        kid.thread_date
    FROM subcategories parent
    INNER JOIN subsubcategories child
        ON child.cat_id = parent.cat_id
    INNER JOIN threads kid
        ON child.extra_cat_id = kid.cat_id
WHERE convert(date,thread_date,108) = (
        SELECT MAX(convert(date,thread_date,108))
        FROM threads
        )



回答2:


Do you need to get a thread with maximal date for every subsubcategory, don't you?

SELECT
  parent.subcat_id,
  parent.subcat_name,
  child.subsubcat_name,
  child.subcat_id,
  child.cat_id,
  kid.thread_name,
  kid.cat_id,
  kid.thread_date
FROM subcategories parent
  JOIN subsubcategories child ON child.cat_id=parent.cat_id
  JOIN threads kid ON kid.cat_id=child.extra_cat_id
WHERE kid.thread_date=
  (SELECT MAX(kid2.thread_date)
   FROM threads kid2
   WHERE kid2.cat_id=child.extra_cat_id)



回答3:


I got this fixed by creating a PHP function to return the latest thread with a

SELECT * FROM threads WHERE subcat_id = variable SQL.



来源:https://stackoverflow.com/questions/41525618/resulting-data-on-last-thread-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!