php - Merge two queries into single query -
i have function gets information database, namely amount of songs in songs table , amount of artists artists table have songs in song table:
function getinfo() { try { $q = $this->connection->prepare('select artist_id '.tbl_song.''); $q->execute(); if ($q->rowcount() > 0) { $songs = $q->rowcount(); } else { $songs = '0'; } $q = $this->connection->prepare('select id '.tbl_artist.' exists (select * '.tbl_song.' s a.id = s.artist_id)'); $q->execute(); if ($q->rowcount() > 0) { $artists = $q->rowcount(); } else { $artists = '0'; } return "<span class='italic'>current songs: </span>".$songs." <span class='italic'>active artists: </span>".$artists; } catch (pdoexception $e) { echo results_error; logerror($e->getmessage()); } }
the first query gets amount of songs song table , returns rowcount variable. second query gets artist id artist table, if have songs in songs table. result of function return both values.
i want able have both these values returned single query. i've tried writing 1 query , fetching results , using count function amount of rows need doesn't seem work. don't know i'm going wrong here. also, pointless checking if row count > 0 if statement , storing in variable it'll return value '0' anyway? thanks.
this pretty easy. want join artist table , song table using artist id. join, want know number of distinct artist ids , song ids. query want this:
select count(distinct a.id) artists, count(distinct s.id) songs artists inner join songs s on s.artist_id = a.id;
i highly recommend query right console of kind before plugging php. output single row looks this:
+---------+-------+ | artists | songs | +---------+-------+ | 20 | 150 | +---------+-------+
from php, need fetch one-row answer , use in response:
if ($q->rowcount() > 0) { $c = $q->fetchobject(); $output = "<span class='italic'>current songs: </span>{$c->songs}<span class='italic'>active artists: </span>{$c->artists}"; }
Comments
Post a Comment