如何检查行是否存在?并获取它为两个表?

时间:2015-08-12 19:49:55

标签: mysql

我有两张桌子:votes | favorites

这是我的结构:

// 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 table:

的结构
// posts
+----+-------+---------+----+-------------+-----------------+
| id | title | content | by | total_votes | total_favorites |
+----+-------+---------+----+-------------+-----------------+

3 个答案:

答案 0 :(得分:3)

不是单独查询以确定当前用户在查询和提取帖子后是否已经投票/收藏,您可以通过向查询检索帖子添加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以确定投票/收藏是否存在。

答案 1 :(得分:1)

使用

SELECT value 
FROM votes 
WHERE 
    id_post={@pid} AND
    id_user={@uid}

会给你(如果数据库是一致的)0或1行包含值。

在DBClient端,您可以检查结果集是否为空,这是对投票存在的隐式检查。

要同时获取帖子和投票,这应该有效(Uodate:纳入收藏夹):

SELECT p.*, v.value
FROM posts p
LEFT JOIN votes v
    ON v.id_post = p.id
LEFT JOIN favorites f
    ON f.id_post = p.id
WHERE 
    p.id={@pid} AND
    v.id_user={@uid} AND
    f.id_user={@uid}

答案 2 :(得分:1)


select 
    p.id_post,
    if(f.favorite is null, 'No', 'Yes') favorite,
    if(v.vote is null, 0, v.vote) vote
from
    posts p
        left join
    (select 
        id_post, id_post favorite
    from
        favorites
    where
        id_user = 100 and id_post = 4) f ON (p.id_post = f.id_post)
        left join
    (select 
        id_post, value vote
    from
        votes
    where
        id_user = 100 and id_post = 4) v ON (p.id_post = v.id_post)
where
    p.id_post = 4;

替换id_post = 4和id_user = 100 当vote为0表示用户尚未评级