我有两个表:votes
| 收藏夹
。
这是我的结构:
// votes // favorite
+----+---------+---------+-------+ +----+---------+---------+
| id | id_post | id_user | value | | id | id_post | id_user |
+----+---------+---------+-------+ +----+---------+---------+
当我显示一个帖子时,我需要知道当前用户是否已经对该帖子进行了投票,如果是,它的值是多少(1 或 -1)?我还需要检查这篇文章是否为当前用户所喜爱?那么我该如何实现呢?
我的尝试:
用于检查现有收藏夹:
SELECT EXISTS(SELECT 1 FROM favorites WHERE post_id={} and user_id={} LIMIT 1) as favorite
我也有相同的查询来检查是否有任何投票?但我想知道如何同时检查和获取?我想知道混合两个查询我应该使用 join
吗?
编辑:
这里还有posts
表的结构:
// posts
+----+-------+---------+----+-------------+-----------------+
| id | title | content | by | total_votes | total_favorites |
+----+-------+---------+----+-------------+-----------------+
最佳答案
与其在已经查询和获取帖子后单独查询以确定当前用户是否投票/收藏,不如通过在查询检索中添加 LEFT JOIN
来显着减少总体查询数量帖子。
SELECT
`posts`.`id`,
`title`,
`content`,
`by`,
`total_votes`,
`total_favorites`,
-- Use a CASE condition to return a value for votes
-- based on whether a row is returned by the LEFT JOIN
-- Change the values like 'has voted' to whatever you want them to be
CASE
WHEN `votes`.`id` IS NOT NULL THEN 'has voted'
ELSE 'has not voted'
END AS `user_has_voted`,
-- Also return the vote value, which will be NULL if no vote exists
`votes`.`value` AS `vote_value`,
-- Do the same for favorites
CASE
WHEN `favorites`.`id` IS NOT NULL THEN 'has favorited'
ELSE 'has not favorited'
END AS `user_has_favorited`
FROM
`posts`
-- Supply the user's id to the ON condition
-- for both of the joins.
LEFT JOIN `votes`
ON `posts`.`id` = `votes`.`id_post`
AND `votes`.`id_user` = <user_id>
LEFT JOIN `favorites`
ON `posts`.`id` = `favorites`.`id_post`
AND `favorites`.`id_user` = <user_id>
这样做将仅在一个查询中完成所有事情。使用 LEFT JOIN
的想法是,如果存在相关表,它将返回值,否则返回 NULL
。因此,在 CASE
语句中,您可以检查 IS NOT NULL
以确定投票/收藏夹是否存在。
关于mysql - 如何检查行是否存在?并为两个表获取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31974153/