简体   繁体   中英

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 has all the information for a given series including its id (column named "seriesid"). And OtherTable has a column called "seriescolumn" which also has the ids of a given series.

I need to make a query that counts every entry in OtherTable's "seriescolumn" that matches the seriesid column in SeriesTable. 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.

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.

    <?
    $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.

You can use a GROUP BY clause to group the result by the seriesid as you want, giving something along the lines of:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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