簡體   English   中英

將兩個查詢合並為一個查詢

[英]Merge two queries into single query

我有一個從數據庫獲取信息的功能,即歌曲表中的歌曲數量和歌手表中具有歌曲表中歌手的歌手數量:

function getInfo() {
    try {
        $q = $this->connection->prepare('SELECT artist_id FROM '.TBL_SONG.'');
        $q->execute();
        if ($q->rowCount() > 0) {
            $songs = $q->rowCount();
        } else {
            $songs = '0';
        }
        $q = $this->connection->prepare('SELECT id FROM '.TBL_ARTIST.' a WHERE EXISTS (SELECT * FROM '.TBL_SONG.' s WHERE 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());
    }
}

第一個查詢從歌曲表中獲取歌曲數量,並將行數返回到變量。 如果歌曲表中有歌曲,則第二個查詢將從歌手表中獲取歌手ID。 該函數的結果是返回兩個值。

我希望能夠從單個查詢返回這兩個值。 我嘗試將其作為一個查詢編寫並獲取結果,並使用count函數獲取所需的行數,但這似乎不起作用。 真的不知道我在哪里出問題了。 另外,使用if語句檢查行數是否> 0是否毫無意義,並將其存儲在變量中,因為它無論如何都會返回值'0'? 謝謝。

這實際上很容易。 您要使用藝術家ID來加入藝術家表和歌曲表。 通過該聯接,您想知道不同的藝術家ID和歌曲ID的數量。 您想要的查詢將是這樣的:

select count(distinct a.id) as artists, count(distinct s.id) as songs
from artists a
inner join songs s on s.artist_id = a.id;

我強烈建議您在將查詢插入到PHP之前,先從某種類型的控制台獲取查詢。 輸出將是一行,看起來像這樣:

+---------+-------+
| artists | songs |
+---------+-------+
|      20 |   150 |
+---------+-------+

從PHP,您只需要獲取單行答案並將其用於響應中:

if ($q->rowCount() > 0) {
    $c = $q->fetchObject();
    $output = "<span class='italic'>Current songs: </span>{$c->songs}<span class='italic'>Active artists: </span>{$c->artists}";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM