0

我很难描述这一点,而且很可能我让这变得比应该的更困难......

基本上,我有一个充满图钉/帖子的页面,用户可以对它们投赞成票或反对票。在一个查询中,我想获得一个 pin 列表,但还要加入两个表以查看用户是否对它们投了赞成票或反对票。

表结构:

pins table

|  id  |       title       |
+------+-------------------+
    1         Post 1
    2         Post 2
    3         Post 3
    4         Post 4

user_upvotes table

|  id  |  user_id  |  pin_id  |
+------+-----------+----------+
   1         1           2
   2         2           1
   3         2           3
   4         2           1

user_downvotes table

|  id  |  user_id  |  pin_id  |
+------+-----------+----------+
   1         2           2
   2         1           1
   3         1           3
   4         1           1

这是我尝试过的查询,但最终复制了页面上的图钉。

SELECT pins.id AS pin_id, title, user_upvotes.id AS upvote, user_downvotes.id AS downvote
FROM pins
LEFT JOIN user_upvotes ON user_upvotes.pin_id = pins.id AND user_upvotes.user_id = 2
LEFT JOIN user_downvotes ON user_downvotes.pin_id = pins.id AND user_downvotes.user_id = 2

这导致(注意 pin_id 1 重复两次):

| pin_id |       title       |  upvote  |  downvote  |
|   1    |       Post 1      |  (NULL)  |      2     |
|   1    |       Post 1      |  (NULL)  |      4     |
|   2    |       Post 2      |     1    |    (NULL)  |
|   3    |       Post 3      |  (NULL)  |      3     |
|   4    |       Post 4      |  (NULL)  |    (NULL)  |

从这一点开始,我只检查该值是否为 NULL,如果不是,我附加一个 css 类以指示它已被赞成或反对。

本质上,我想要上面的结果,只是没有复制引脚。如果您有更好的方法,请随时告诉我。

4

3 回答 3

1

添加分组依据

SELECT pins.id AS pin_id, title, user_upvotes.id AS upvote, user_downvotes.id AS downvote
FROM pins
LEFT JOIN user_upvotes ON user_upvotes.pin_id = pins.id AND user_upvotes.user_id = 2
LEFT JOIN user_downvotes ON user_downvotes.pin_id = pins.id AND user_downvotes.user_id = 2
GROUP BY pin_id
于 2012-12-12T22:13:27.297 回答
1

这可能意味着用户对同一个 pin 投了两次赞成票或反对票。由于您在结果中包含投票的 ID,因此您将不同的投票作为单独的记录获得。

我认为您要么想要计数,要么根本想要防止双重投票。计数如下:

SELECT 
  pins.id AS pin_id, 
  title, 
  COUNT(user_upvotes.id) AS upvotes, 
  COUNT(user_downvotes.id) AS downvotes
FROM pins
LEFT JOIN user_upvotes ON user_upvotes.pin_id = pins.id AND user_upvotes.user_id = 2
LEFT JOIN user_downvotes ON user_downvotes.pin_id = pins.id AND user_downvotes.user_id = 2
GROUP BY 
  pins.id

现在您可以显示计数,或者仅将其显示为是或否,具体取决于它是否 > 0。

于 2012-12-12T22:20:58.363 回答
-1

这不会有帮助吗?

 SELECT pins.id AS pin_id, title, user_upvotes.id AS upvote, user_downvotes.id AS downvote
 FROM pins
 LEFT JOIN user_upvotes ON user_upvotes.pin_id = pins.id AND user_upvotes.user_id = 2
 LEFT JOIN user_downvotes ON user_downvotes.pin_id = pins.id AND user_downvotes.user_id = 2
 **GROUP BY pins.id**
于 2012-12-12T22:14:22.337 回答