将两个查询合并为单个查询

时间:2013-05-18 18:07:06

标签: php mysql

我有这个函数从数据库中获取信息,即歌曲表中的歌曲数量和艺术家表中有歌曲表中歌曲的艺术家数量:

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());
    }
}

第一个查询获取歌曲表中的歌曲数量,并将rowcount返回给变量。第二个查询从艺术家表中获取艺术家ID,如果他们在歌曲表中有歌曲。此函数的结果是返回两个值。

我希望能够从单个查询中返回这两个值。我已经尝试将其编写为一个查询并获取结果并使用count函数来获取我需要的行数但这似乎不起作用。真的不知道我在哪里错了。另外,检查行数是否> 1是毫无意义的。 0带有if语句并将其存储在变量中,因为它会返回值'0'吗?感谢。

1 个答案:

答案 0 :(得分:1)

这实际上非常简单。您想使用艺术家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}";
}