Query Topics & Categories from multiple tables
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)
精彩评论