查询我正在关注的用户的所有帖子和我自己的帖子

时间:2015-05-14 12:44:09

标签: php mysql sql

我有三张桌子

  1. 用户> id, username, name, age, sex, location
  2. 用户帖子> id, user_id, description, image, postime, location
  3. 关注> id, user_id, follow_id, status
  4. 在用户表中,我将获得所有用户信息。

    在“用户帖子”表格中,我将获得所有与帖子相关的信息。

    我想显示自己的帖子以及我关注的用户的帖子

    我为这种情况编写的查询是

    SELECT 
      u.username,
      u.name,
      u.profile_pic, 
      up.* 
     FROM user u, user_post up 
     WHERE (up.user_id  = $user_id OR up.user_id IN 
           (SELECT user_id 
            FROM follow WHERE follow_id=$user_id)), $user_id) 
            AND description='' group by id order by postime desc
    

    我觉得查询错了,任何人都可以帮助我

    CREATE TABLE IF NOT EXISTS `user` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL,
      `username` varchar(30) NOT NULL,
      `password` varchar(1000) NOT NULL,
      `email` varchar(100) NOT NULL,
      `age` varchar(100) NOT NULL,
      `gender` varchar(100) NOT NULL,
      `city` varchar(100) NOT NULL,
      `state` varchar(100) NOT NULL,
      `country` varchar(100) NOT NULL,
      `profile_pic` varchar(100) NOT NULL,
      `deviceToken` char(64) DEFAULT NULL,
      PRIMARY KEY (`id`)
    )
    
    CREATE TABLE IF NOT EXISTS `user_post` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `description` varchar(100) NOT NULL,
      `image` varchar(100) NOT NULL,
      `location` varchar(100) NOT NULL,
      `postime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
      `user_id` int(20) NOT NULL,
      PRIMARY KEY (`id`)
    )
    
    CREATE TABLE IF NOT EXISTS `follow` (
      `id` int(100) NOT NULL AUTO_INCREMENT,
      `user_id` int(100) NOT NULL,
      `follow_id` int(100) NOT NULL,
      `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      `status` varchar(20) NOT NULL DEFAULT 'Pending',
      PRIMARY KEY (`id`)
    )
    

1 个答案:

答案 0 :(得分:1)

这与我昨天发布的答案相同:

SELECT u.username,u.name,u.profile_pic, up.* 
FROM user u JOIN user_post up 
  ON up.user_id = u.id
WHERE 
   (up.user_id  = $user_id 
    OR
    up.user_id IN (
                     SELECT user_id 
                     FROM follow 
                     WHERE follow_id=$user_id
                   )
   )
AND description='' 
ORDER BY postime DESC

由于您没有说明用户与关注者之间的关系,因此可能需要切换follow_iduser_id

SELECT u.username,u.name,u.profile_pic, up.* 
FROM user u JOIN user_post up 
  ON up.user_id = u.id
WHERE 
   (up.user_id  = $user_id 
    OR
    up.user_id IN (
                     SELECT follow_id
                     FROM follow 
                     WHERE user_id=$user_id
                   )
   )
AND description='' 
ORDER BY postime DESC