内部联接以计算行和顺序

时间:2016-07-12 02:13:22

标签: php oracle pdo

我试图阅读有关某些用户的一些内容,但是,我会执行3个查询来计算"关注"和" LINKS",我知道可以通过一个查询,使用内部联接等来实现。我不知道如何做到这一点,有人可以帮助我吗?

我是brazillian,抱歉英语不好。

$Read = new Read();
$Read->FullRead("SELECT AUTHORS_NAME, AUTHORS_LASTNAME, AUTHORS_PHOTO, AUTHORS_FRIENDLY_URL, AUTHORS_ID FROM AUTHORS");

if ($Read->getResult()):
    foreach ($Read->getResult() as $AUTHORS):
        extract($AUTHORS);

        $COUNT = 0;
        $READ_FOLLOWER = new Read();
        $READ_FOLLOWER->FullRead("SELECT AUTHORS_ID FROM FOLLOWERS WHERE AUTHORS_ID = {$AUTHORS_ID}");
        if ($READ_FOLLOWER->getResult()):
            foreach ($READ_FOLLOWER->getResult() as $READ_FOLLOWER_ITEM):
                $COUNT++;
            endforeach;
        endif;

        $LINK_COUNT = 0;
        $READ_LINKS = new Read();
        $READ_LINKS->FullRead("SELECT LINK_AUTHORS FROM LINKS WHERE LINK_AUTHORS = {$AUTHORS_ID}");
        if ($READ_LINKS->getResult()):
            foreach ($READ_LINKS->getResult() as $READ_LINKS_ITEM):
                $LINK_COUNT++;
            endforeach;
        endif;

        //ECHO ON ALL VARIABLES

    endforeach;
endif;

2 个答案:

答案 0 :(得分:1)

使用一个查询,您可以尝试:

SELECT A.AUTHORS_NAME, A.AUTHORS_LASTNAME, A.AUTHORS_PHOTO, A.AUTHORS_FRIENDLY_URL, A.AUTHORS_ID,
   COALESCE(T1.CNT, 0) AS FOLLOWERS_CNT,
   COALESCE(T2.CNT, 0) AS LINKS_CNT
FROM AUTHORS A
LEFT JOIN (
    SELECT AUTHORS_ID, COUNT(1) AS CNT FROM FOLLOWERS GROUP BY AUTHORS_ID
) T1 ON A.AUTHORS_ID = T1.AUTHORS_ID
LEFT JOIN (
    SELECT LINK_AUTHORS, COUNT(1) AS CNT FROM LINKS GROUP BY LINK_AUTHORS
) T2 ON A.AUTHORS_ID = T2.LINK_AUTHORS
ORDER BY T1.CNT, T2.CNT DESC

答案 1 :(得分:0)

对此使用子查询,您可以在一行中获得关注者和链接的总行数

console.log(obj[0].date);