简体   繁体   English

带子查询的SQL

[英]SQL with subqueries

I remember doing this in DB class in what feels like ages ago, but can't recall it and can't seem to search for the right words. 我记得很早以前在DB类中进行过此操作,但无法回忆起,也似乎无法搜索正确的单词。

I am trying to essentially turn a query that produces a foreach and then runs another query based on information from the first one, into one query. 我实际上试图将一个查询生成一个foreach,然后根据来自第一个查询的信息运行另一个查询,成为一个查询。 More clearly, I have two tables members and entries. 更清楚地说,我有两个表成员和条目。 For our purposes members has two columns member_id, member_name, and entries has entry_id, channel_id, author_id. 为了我们的目的,成员具有两列member_id,member_name,条目具有entry_id,channel_id,author_id。 Author_id is an FK to member_id. Author_id是member_id的FK。

I want a count of entries by each author and do it in one SQL statement. 我想要每个作者的条目计数并在一个SQL语句中执行。 So I need a list of the member id's first then take each member id and query the entries table for the count of entries where author_id = member_id. 因此,我需要首先获得成员ID的列表,然后获取每个成员ID,并在entrys表中查询author_id = member_id的条目数。

Programmatically it would look something like this (not full code obvi): 以编程方式,它看起来像这样(不是完整的代码):

$mems = select member_id from members_table;
foreach($mems as $cur_mem) {
    $entry_count = select count(*) from entries_table where author_id=$cur_mem[member_id];
    echo $entry_count;
}

This is for MySQL and using a CMS called ExpressionEngine, which is the cause of this headache of a solution. 这是针对MySQL的,并使用一个称为ExpressionEngine的CMS,这是导致解决方案头痛的原因。 Having a hard time describing this issue, so I can clarify any questions. 很难描述这个问题,因此我可以澄清所有问题。

Thanks! 谢谢!

Try this query: 试试这个查询:

SELECT member_id, 
       COUNT(author_id ) 
FROM   members_table m 
       INNER JOIN entries_table 
         ON author_id = member_id 
GROUP  BY member_id 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM