简体   繁体   English

计算第二个表中与第一个表中的ID相匹配的条目

[英]Count entries from second Table that match id from first Table

This is basic but I can't figure it out. 这是基本的,但我不知道。 I have two tables (SeriesTable and OtherTable). 我有两个表(SeriesTable和OtherTable)。 SeriesTable has all the information for a given series including its id (column named "seriesid"). SeriesTable具有给定系列的所有信息,包括其ID(名为“ seriesID”的列)。 And OtherTable has a column called "seriescolumn" which also has the ids of a given series. 另外,OtherTable有一个名为“ seriescolumn”的列,该列也具有给定序列的ID。

I need to make a query that counts every entry in OtherTable's "seriescolumn" that matches the seriesid column in SeriesTable. 我需要进行查询,以计算OtherTable的“ seriescolumn”中与SeriesTable中的seriesid列匹配的每个条目。 So for example, if the seriesid in SeriesTable is 5, I need to count how many entries in OtherTable have the value of 5 in the seriescolumn. 因此,例如,如果SeriesTable中的seriesid为5,我需要计算OtherTable中有多少条目在series列中的值为5。

Below is my current code that simply grabs the info from the first table, but I have no idea how to correctly count the matching entries from OtherTable. 下面是我当前的代码,该代码只是从第一个表中获取信息,但是我不知道如何正确地从OtherTable中计数匹配的条目。

    <?
    $rs= mysql_query("SELECT seriesid FROM SeriesTable ORDER BY seriesid DESC");
    while ($row= mysql_fetch_array($rs)) { ?>

    content

    <? } ?>

Sounds like you are going to need a join and group by statement. 听起来您需要联接和按语句分组。

SELECT  s.seriesid, Count(*) As NumberOfSeries
FROM    SeriesTable s Join
        OtherTable o On s.seriesid = o.seriescolumn
Group By s.seriesid
ORDER BY seriesid DESC

This should return each seriesid and a count of how many times it was repeated. 这应该返回每个序列号以及其重复次数的计数。

Probably the easiest way to do this is in one big SQL query, using the count statement. 可能最简单的方法是在一个大型SQL查询中使用count语句。

You can use a GROUP BY clause to group the result by the seriesid as you want, giving something along the lines of: 您可以使用GROUP BY子句根据需要按序列号对结果进行分组,并提供以下内容:

SELECT seriesid, COUNT(*) FROM SeriesTable, OtherTable 
WHERE seriescolumn=seriesid GROUP BY seriesid
SELECT seriesid, COUNT(seriescolumn)
FROM SeriesTable, OtherTable 
WHERE OtherTable.seriescolumn = SeriesTable.seriesid
GROUP BY seriesid;

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

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