从mysql中的2个表中获取数据(需要帮助)

时间:2012-02-13 19:18:10

标签: php mysql sql phpmyadmin

我有两张桌子..

第一张表:帖子

|post_id  |    post_data |
..........................
|   1     |    any data  |
|   2     |    any data  |
|   3     |    any data  |

第二张表:post_likes

|like_id  |    post_id   | by_user |
....................................
|   1     |      1       |   3     |
|   2     |      3       |   3     |

当任何用户像任何帖子数据一样存储在posts_likes表中时.. 我想显示用户3不喜欢的帖子(来自两个表一次)..

我正在使用此查询

SELECT *
FROM post, post_likes
WHERE post.post_id != post_likes.post_id
AND by_user=3

它向我展示了这些结果..

post_id     post_data   like_id     post_id     by_user
  1         my data       2            3          3
  2         my data       1            1          3
  2         my data       2            3          3
  3         my data       1            1          3

但它应该只显示post_id = 2的结果(因为用户喜欢post_id 1和3)

正确的查询是什么,我可以通过该查询获得用户3不喜欢的帖子

4 个答案:

答案 0 :(得分:2)

select *
from posts
where post_id not in
(
    select post_id
    from post_likes
    where by_user = 3
)

答案 1 :(得分:0)

您可以在NOT IN ()子句中使用WHERE子查询:

SELECT
  posts.post_id,
  posts.post_data,
  post_likes.like_id,
  post_likes.by_user
FROM posts LEFT JOIN post_likes ON posts.post_id = post_likes.post_id
WHERE posts.post_id NOT IN (
  SELECT DISTINCT post_id FROM post_likes WHERE by_user = 3
)

答案 2 :(得分:0)

SELECT *
    FROM post p
        LEFT JOIN post_likes pl
            ON p.post_id = pl.post_id
    WHERE NOT EXISTS (SELECT 1
                          FROM post_likes pl2
                          WHERE pl2.post_id = p.post_id
                              AND pl2.user_id = 3);

答案 3 :(得分:0)

SELECT *
FROM post p
WHERE NOT EXISTS (SELECT * 
                  FROM post_likes 
                  WHERE p.post_id = post_likes.post_id 
                    AND user_id = 3
                 )