PHP投票系统检查投票

时间:2016-06-25 07:09:40

标签: php mysql

我正在开发一个PHP投票系统,我想检查登录用户投票的帖子和显示投票,如果用户投票。我想在一个查询中执行它而不使用多个quires。 帖子表

+---------+--------+--------+
| post_id | title  | c_id   |   
+---------+--------+--------+
|       1 | post 1 |   2    |
|       2 | post 2 |   3    | 
|       3 | post 3 |   2    | 
|       4 | post 4 |   1    |
+---------+--------+--------+

MySQL循环

SELECT * 
  FROM posts 
  LEFT 
  JOIN categories 
    ON categories.cat_id = posts.c_id 
 WHERE posts.c_id = categories.cat_id 
   AND posts. active = 1 
 ORDER 
    BY posts.post_id DESC 
 LIMIT 0, 10

投票表

+---------+--------+---------+
| vote_id | p_id   | u_id    |  
+---------+--------+---------+
|       1 |   1    |   1     |
|       2 |   2    |   1     | 
|       3 |   2    |   2     | 
|       4 |   4    |   1     |
+---------+--------+---------+

登录user = $uid 因此,如果我在上面的MySQL循环中运行查询它可以正常工作

SELECT * FROM votes WHERE u_id = $uid AND p_id= $post_id

有没有办法合并这两个查询?

4 个答案:

答案 0 :(得分:3)

SELECT * 
  FROM posts P
  LEFT 
  JOIN categories C
    ON C.cat_id = P.c_id 
  LEFT JOIN (SELECT p_id FROM votes WHERE u_id = $uid)  V 
    ON V.p_id=P.post_id
   WHERE P. active = 1  
 ORDER 
    BY P.post_id DESC 
 LIMIT 0, 10 ;

答案 1 :(得分:1)

LEFT JOIN投票表(如果您不想要空联接,也不需要左连接类别)。如果用户已投票,则会在连接列中显示值 - 否则将加入空值。

SELECT *
FROM posts AS p
INNER JOIN categories AS c ON c.cat_id = p.c_id
LEFT JOIN votes AS v ON p.post_id = v.p_id AND v.u_id = $uid
WHERE p.active = 1
ORDER BY p.post_id DESC
LIMIT 0, 10

未投票的帖子在投票列中会有空值,但由于您只想知道用户是否投票,您可能会限制输出数据(只获得您需要的内容)指定具体字段并使voted列返回1 /仅限0值:

SELECT p.*, c.title, ..., IF(v.vote_id; 1; 0) AS voted

答案 2 :(得分:0)

您可以使用针对投票表和帖子表中的常用字段的联接,如下所示:

    <?php
        $sql  = "SELECT * FROM votes AS V LEFT JOIN posts AS P ON V.p_id=P.post_id 
                 WHERE (V.u_id={$uid} AND V.p_id={$post_id}) GROUP BY V.u_id";

答案 3 :(得分:0)

您无法在列中选择投票作为数组,但您实际上可以提取投票并对其进行分组。所以基本上我们要做的就是部分地加入两个表并且可以总结所有的投票

SELECT p.*, c.*, sum(v.Score) FROM posts p LEFT JOIN categories c ON c.cat_id = p.c_id LEFT JOIN votes v ON p.post_id = v.p_id WHERE p.active = 1 AND v.u_id = $uid GROUP BY p.post_id ORDER BY p.post_id DESC LIMIT 0, 10

你可以看到我总结了投票中的所有分数,以防重复

相关问题