带有子查询的 SQL
我记得在数据库课上做过这件事,感觉像是很久以前的事,但记不起,似乎无法搜索正确的单词。
我试图本质上将一个生成 foreach 的查询,然后根据第一个查询的信息运行另一个查询,转换为一个查询。更清楚地说,我有两个表成员和条目。出于我们的目的,成员有两列member_id、member_name,条目有entry_id、channel_id、author_id。 Author_id 是member_id 的外键。
我想要计算每个作者的条目数,并在一个 SQL 语句中完成。因此,我首先需要一个成员 id 的列表,然后获取每个成员 id 并查询条目表以获取author_id = member_id 的条目数。
从编程角度来看,它看起来像这样(不是完整的代码 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;
}
这是针对 MySQL 的,并使用名为 ExpressionEngine 的 CMS,这就是解决方案中令人头疼的原因。很难描述这个问题,所以我可以澄清任何问题。
谢谢!
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.
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. 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. Author_id is an FK to member_id.
I want a count of entries by each author and do it in one SQL statement. 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.
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. Having a hard time describing this issue, so I can clarify any questions.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个查询:
Try this query: