[英]How to count all rows in a joined table with a specific ID
我有两张桌子,一张是歌曲列表。 另一个是项目清单。
它们由songsID加入。 我的查询目前看起来像这样: -
$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());
$ sTable和$ sTable2变量清楚地表示两个表。
这很好,并列出了'$ sTable'中的所有行。 您在上面看到的JOIN并不是列出歌曲所必需的,但就我能够利用我有限的MySQL能力而言。
我想要做的是在我的JSON数据中返回另一列,显示'$ sTable'中每首歌曲的所有项目的总COUNT(在$ sTable2中)。 因此,计算具有特定'songsID'的每个项目。
$ 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' );
这些是$ sTable中的列,其中'songsID'是自动增量主键,它也存储在'$ sTable2'中以将歌曲链接到他们的项目。
我需要能够将'projects_count'添加到上面的$ aColumns数组中。
希望这次我能更好地解释自己。 抱歉,我的SQL经验绝对是最小的。
select count(*) as projects_count, a.songs_id
from Table2 a
group by a.songs_id
这将为您提供每个songs_id
的项目数。
您还可以使用以下命令查询特定的song_id:
select count(*) as projects_count
from Table2 where Table2.songs_id = <your_song_id>
和这个:
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.