简体   繁体   中英

sql join a single entry with the sum of multiple entry table

i have a table that stores a single entry post (POSTS) and another table that stores multiple entries of users that like a post. the user_id and the date the post was liked. (POSTLIKES)

How can i write a single query that will select each post from post table and count the number of entries as sum on the postlikes table where posts.id = postlikes.post_id.

Preferable answers in SQL and the laravel equivalent. Any would do. Thanks

采用 :

Select COUNT(postlikes.id), postlikes.post_id, posts.name as post_name from postlikes inner join postlikes on posts.id = postlikes.post_id group by postlikes.post_id

By GROUPing BY the the post id.
The aggregate functions (like Count()) will work on each group, ie for each group one record will be returned.
You can also SEELCT the group discriminator (the post id in this case). And MySQL is somewhat lax on the rules, so you can also select just any field from the "posts" table as well - but unless you really have to ....don't ;-)

sscce :

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');  
//echo 'client version: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
//echo 'server version: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);


$result = $pdo->query('
    SELECT
        p.id, Count(l.user_id) as lc
    FROM
        soPosts as p
    LEFT JOIN
        soLikes as l
    ON
        l.post_id=p.id
    GROUP BY
        p.id
', PDO::FETCH_ASSOC);

foreach($result as $row ) {
    echo join(', ', $row), "\r\n";
}



function setup($pdo) {
    $queries = array(
        '
            CREATE TEMPORARY TABLE soPosts (
                id INT auto_increment,
                title varchar(32),
                message varchar(32),
                primary key(id)
            )
        ',
        '
            CREATE TEMPORARY TABLE soLikes (
                post_id INT,
                user_id INT,
                primary key(post_id,user_id)
            )
        ',
        "INSERT INTO soPosts (title,message) VALUES
            ('PostA', 'messageA'),('PostB', 'messageB'),('PostC', 'messageC'),('PostD', 'messageD')
        ",
        'INSERT INTO soLikes (post_id,user_id) VALUES
            (1, 1),(1, 2),(1, 3),(1, 4),(1, 5),
            (2, 4),(2, 5),
            (3, 1)
        ',
    );
    foreach( $queries as $q ) {
        $pdo->exec($q);
    }
}

prints

1, 5
2, 2
3, 1
4, 0

(as expected: everybody likes post #1, no one likes #4)

尝试这个

$query="SELECT tbl1.col1, tbl1.col2, tbl2.col1, tbl2.col2 from POSTS as tbl1 inner join POSTLIKES as tbl2 on tbl1.post_id=tbl2.post_id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM