我有两个表,一个是歌曲列表。另一个是项目列表。
它们由歌曲ID 连接起来。我的查询目前如下所示:-
$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”中每首歌曲的所有项目(在 $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
关于php - 如何计算具有特定 ID 的连接表中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968783/