0

one more time I turn to you for asking about mysql, definitely not my best skill. In fact, seems not to be very complex. This is my simplified scenario, I have two tables, one for posts, another for likes to posts:

Table post_forum structure

id     thread    post   likes   user_id    created    

Table likes_to_post structure

id     post_id   user_id   created

This is my query for obtain posts from $start to $next for a thread $thread_id:

 $query = "SELECT 
                post_forum.id,
                post_forum.user_id,
                post_forum.post, 
                post_forum.likes,
                post_forum.created 
            FROM post_forum 
            WHERE post_forum.thread ='{$thread_id}' 
            ORDER BY post_forum.id DESC LIMIT $start,$next";

What I want to do is get por every post, a 0 or 1 value for a field saying if the user $user_id has liked every post, being $user_id the id of user that asks the post, in one query if possible. Thanks a lot in advance, any help is appreciated.

4

2 回答 2

2

You would need a query like this:

SELECT p.id, CASE WHEN l.id IS NULL THEN 0 ELSE 1
FROM post_forum p
LEFT JOIN likes_to_post l
  ON l.post_id = p.id
  AND l.user_id = ?

This does assume you're using PDO with parameterized queries. The query takes the user id as its only parameter.

于 2013-08-10T10:00:36.157 回答
1
$query = "SELECT 
            a.id,
            a.user_id,
            a.post, 
            a.likes,
            a.created,
            IF(b.user_id IS NOT NULL,1,0)
        FROM post_forum a
        LEFT JOIN likes_to_post b
            ON b.user_id=$user_id AND a.id = b.post_id
        WHERE a.thread ='{$thread_id}' 
        ORDER BY a.id DESC LIMIT $start,$next";

这是查询:1如果喜欢则返回,0如果不喜欢则返回:
但是您应该使用mysqliPDO来防止安全攻击

编辑
Mysqli 示例(我不确定 thread_id,我想它是一个数字):

$query = "SELECT 
        a.id,
        a.user_id,
        a.post, 
        a.likes,
        a.created,
        IF(b.user_id IS NOT NULL,1,0)
    FROM post_forum a
    LEFT JOIN likes_to_post b
        ON b.user_id=? AND a.id=b.post_id
    WHERE a.thread ='{?}' 
    ORDER BY a.id DESC LIMIT ?,?";
//Connect to datatabase
$mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
$stmt = $mysqli->stmt_init();
$stmt->prepare($query);
    $stmt->bind_param('iiii', $user_id,$thread_id,$start,$next)
        $stmt->execute()
            $stmt->store_result();
            $result = $stmt->bind_result($id, $user_id, $post, $likes, $created,$liked);
            if($stmt->num_rows>0){
                while (mysqli_stmt_fetch($stmt)) {
                    [Do something]
                }
            }
于 2013-08-10T10:02:23.493 回答