Mysql 查询,用于获取相应的表有记录的结果


Mysql Query for fetching result if corresponding table has records

我想从一个表中获取记录,如果相应的表有记录。

我正在使用这个查询.

SELECT `category_name`, `id` as cat_id FROM categories  WHERE (SELECT count(id)> 0 FROM `articles` where `category_id` = cat_id)  ORDER by `category_name` ASC

它抛出错误不知道cat_id

任何想法。如何做到这一点

谢谢

内部连接可以做到这一点

select
c.category_name,
c.id as cat_id FROM categories c
join articles a on a.category_id = c.id
order by c.category_name

为了提高性能,请确保已为连接键编制索引

我建议有一些东西

alter table categories add index id_idx(id);
alter table categories add index category_name_idx(category_name);
alter table articles add index category_id_idx(category_id)