[英]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. 它们由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. $ sTable和$ sTable2变量清楚地表示两个表。
This works fine and lists all the rows I have in '$sTable'. 这很好,并列出了'$ 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. 您在上面看到的JOIN并不是列出歌曲所必需的,但就我能够利用我有限的MySQL能力而言。
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'. 我想要做的是在我的JSON数据中返回另一列,显示'$ sTable'中每首歌曲的所有项目的总COUNT(在$ sTable2中)。 Therefore counting each project which has a specific 'songsID'. 因此,计算具有特定'songsID'的每个项目。
$aColumns is the following:- $ aColumns如下: -
$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. 这些是$ sTable中的列,其中'songsID'是自动增量主键,它也存储在'$ sTable2'中以将歌曲链接到他们的项目。
I need to be able to add 'projects_count' into the $aColumns array above. 我需要能够将'projects_count'添加到上面的$ aColumns数组中。
Hopefully I have explained myself better this time. 希望这次我能更好地解释自己。 Apologies that my SQL experience is absolutely minimal. 抱歉,我的SQL经验绝对是最小的。
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
. 这将为您提供每个songs_id
的项目数。
You can also query for specific song_id with: 您还可以使用以下命令查询特定的song_id:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.