简体   繁体   中英

How to count all rows in a joined table with a specific ID

I have two tables, one is a list of songs. The other is a list of projects.

They are joined by the songsID. My query currently looks like this:-

$sQuery = "
        SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        LEFT JOIN
            $sTable2
            ON ($sTable2.songs_id = $sTable.songsID)
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error()); 

The $sTable and $sTable2 variables are the two tables clearly.

This works fine and lists all the rows I have in '$sTable'. The JOIN that you see above is not necassary to list the songs but is as far as I am able to get with my limited MySQL ability.

What I would like to do is have another column returned in my JSON data that displays the total COUNT of all projects (in $sTable2) for EACH song in '$sTable'. Therefore counting each project which has a specific 'songsID'.

$aColumns is the following:-

$aColumns = array( 'song_name', 'artist_band_name', 'author', 'song_artwork', 'song_file', 'genre', 'song_description', 'uploaded_time', 'emotion', 'tempo', 'songsID', 'user', 'happiness', 'instruments', 'similar_artists', 'play_count' );

These are the columns in $sTable, with 'songsID' being the auto increment primary key which is also stored in '$sTable2' to link the songs to their projects.

I need to be able to add 'projects_count' into the $aColumns array above.

Hopefully I have explained myself better this time. Apologies that my SQL experience is absolutely minimal.

select count(*) as projects_count, a.songs_id
from Table2 a
group by a.songs_id

This will give you the number of projects per songs_id .

You can also query for specific song_id with:

select count(*) as projects_count
from Table2 where Table2.songs_id = <your_song_id>

And this:

select b.*, bb.projects_count from Table b 
left join (
   select count(*) as projects_count, a.songs_id
   from Table2 a
   group by a.songs_id
) bb on bb.songs_id = b.songsID

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