Home  >  Article  >  Backend Development  >  怎么根据主表ID查询从表对应外键的数据的条数?

怎么根据主表ID查询从表对应外键的数据的条数?

WBOY
WBOYOriginal
2016-06-06 20:17:391492browse

比如从表的reid指向主表的id字段 怎么根据主表的id查询对应的从表外键的数据的条数? 比如reid为1的都指向主表的id为1的行 那么如果只有id 能根据id查询有多少条数据吗?
怎么根据主表ID查询从表对应外键的数据的条数?

回复内容:

比如从表的reid指向主表的id字段 怎么根据主表的id查询对应的从表外键的数据的条数? 比如reid为1的都指向主表的id为1的行 那么如果只有id 能根据id查询有多少条数据吗?
怎么根据主表ID查询从表对应外键的数据的条数?

You need [JOIN]

比如主表为a,从表为b,那么大概可以这样写:

<code>SELECT a.id,COUNT(b.reid) AS count_id FROM a INNER JOIN b ON a.id = b.reid GROUP BY a.id ORDER BY a.id, count_id;</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn