开发者

Query Topics & Categories from multiple tables

开发者 https://www.devze.com 2023-03-10 00:10 出处:网络
I\'m having an issue with MySQL. I have two tables, categories a开发者_运维技巧nd topics.I want to select all of the categories and join topics where categories.id equals the max topics.id where topic

I'm having an issue with MySQL. I have two tables, categories a开发者_运维技巧nd topics. I want to select all of the categories and join topics where categories.id equals the max topics.id where topics.cat_id equals categories.id. Basically I am trying to show a list of categories and then the most recent topic under that category.

Here is my select statement so far:

SELECT
    *
FROM 
    categories 
LEFT JOIN 
    topics 
ON 
    categories.cat_id = (SELECT 
                             MAX(topics.id), topic_cat 
                         FROM 
                             topics 
                         WHERE 
                             topic_cat = categories.cat_id)
GROUP BY 
    categories.cat_id

How can I efficiently do that? I'm getting an error "Operand should contain 1 column(s)".


You should consider updating your select clause to only pull the columns you need from both tables (there will likely be duplicate columns with *), but give this a shot:

select *
from categories c
left join topics t
     on c.cat_id = t.topic_cat
     and t.id = (select MAX(id) from topics where topic_cat = c.cat_id)
0

精彩评论

暂无评论...
验证码 换一张
取 消