如果用户要求喜欢该帖子,则获取帖子的帖子和0或1

时间:2013-08-10 09:41:09

标签: mysql sql

再一次,我转向你询问mysql,绝对不是我最好的技巧。事实上,似乎并不是很复杂。这是我简化的场景,我有两个表,一个用于帖子,另一个用于喜欢帖子:

表post_forum结构

id     thread    post   likes   user_id    created    

表likes_to_post结构

id     post_id   user_id   created

这是我的查询,以获取线程$ thread_id:

从$ start到$ next的帖子
 $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";

我想要做的是获取每个帖子,01字段值,表示用户$user_id是否喜欢每个帖子,$user_id如果可能,在一个查询中询问帖子的用户的ID。 非常感谢,提供任何帮助。

2 个答案:

答案 0 :(得分:2)

您需要这样的查询:

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 = ?

这假设您正在使用带参数化查询的PDO。该查询将用户标识作为其唯一参数。

答案 1 :(得分: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来防止安全攻击< / p>

修改
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]
                }
            }