【问题标题】:MySQL Select rows where the user has not voted yet (contest app)MySQL 选择用户尚未投票的行(竞赛应用程序)
【发布时间】:2015-06-02 12:16:30
【问题描述】:

我有一个摄影比赛应用,用户可以在其中投票。我想选择登录用户尚未投票的所有比赛。

所以我有两张桌子。

“比赛”表:

CREATE TABLE `contest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `desc` text NOT NULL,
  `created_date` datetime NOT NULL,
  `started_date` datetime NOT NULL,
  `nb_user_min` int(11) NOT NULL,
  `nb_photo_max` int(11) NOT NULL,
  `nb_photo_per_user` int(11) NOT NULL,
  `duration` int(11) DEFAULT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

“contest_vote”表:

CREATE TABLE `contest_vote` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `pic_id` int(11) DEFAULT NULL,
  `contest_id` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `ip` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

所以要明确一点,我想获取用户尚未投票的比赛的数量(或列表)。所以我尝试了LEFT JOIN,但它没有返回好的结果集。这是我到目前为止的查询:

SELECT DISTINCT c.id, c.title, cv.user_id
FROM contest c
LEFT JOIN contest_vote cv
ON cv.contest_id = c.id AND cv.user_id != ?
GROUP BY contest_id

("?"代表user_id参数)。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    使用子查询非常简单。只需像这样在没有用户投票的情况下抓住所有比赛:

    SELECT DISTINCT c.id, c.title
    FROM contest c
    WHERE c.id NOT IN (SELECT DISTINCT cv.contest_id FROM contest_vote cv WHERE cv.user_id = ?)
    

    【讨论】:

    • 正是我需要的!非常感谢!
    【解决方案2】:

    试试这个:

    SELECT DISTINCT c.id, c.title, cv.user_id
    FROM contest c
    LEFT JOIN contest_vote cv ON cv.contest_id = c.id AND cv.user_id != ? WHERE c.user_id = ?
    GROUP BY contest_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2020-01-20
      • 1970-01-01
      相关资源
      最近更新 更多