1

我有 2 个表,其值如下:

tbl_users

user_ID      name     
1          somename1   
2          somename2   
3          somename3   

tbl_interviews

int_ID     user_ID      answer          date      
 1            1         sometextaba   2012-11-04 
 2            2         sometextxcec  2012-10-05
 3            1         sometextabs   2011-06-04
 4            3         sometextxcfc  2012-11-04
 5            3         sometextxcdn  2012-11-04

我怎么能问mysql告诉我谁是上表中唯一一个今年接受采访但前几年又接受过采访的用户?唯一一个是 id = 1 的用户(因为他今年接受了采访(int_id 1),但第一次采访是在 2011 年(int-id 3)。)不幸的是,我什至无法选择它们。 .

4

4 回答 4

2

通过将表格与自身连接起来,其中连接的一侧仅包括今年的采访,而另一侧仅包括前几年的采访,结果INNER JOIN将是用户同时拥有两者。

因为它不需要依赖任何聚合或子查询,所以这种方法应该非常高效。特别是如果该date列有索引。

SELECT
  DISTINCT
  thisyear.user_ID,
  name
FROM
  /* Left side of join retrieces only this year (year=2012) */
  tbl_interviews thisyear
  /* Right side retrieves year < 2012 */
  /* The combined result will elmininate any users who don't exist on both sides of the join */
  INNER JOIN tbl_interviews previous_years ON thisyear.user_ID = previous_years.user_ID
  /* and JOIN in the user table to get a name */
  INNER JOIN tbl_users ON tbl_users.user_ID = thisyear.user_ID
WHERE
  YEAR(thisyear.date) = 2012
  AND YEAR(previous_years.date) < 2012

这是关于 SQLFiddle 的演示

于 2012-11-10T14:40:17.617 回答
1

一种简单的方法,可能效率低于JOINs

SELECT DISTINCT user_ID
FROM   tbl_interviews
WHERE  user_ID IN (
                   SELECT   user_ID
                   FROM     tbl_interviews 
                   WHERE    date < 2012-01-01
                  ) 
   AND user_ID IN (
                   SELECT   user_ID
                   FROM     tbl_interviews 
                   WHERE    date > 2012-01-01
                  )          
于 2012-11-10T14:48:25.407 回答
1

以下为您提供当年接受采访的用户,只有那些也出现在上一年的用户

SELECT Distinct tc.user_ID  FROM  tbl_interviews tc
INNER JOIN tbl_interviews tp ON tc.user_ID = tp.user_ID
WHERE YEAR(tc.date) = Year(curDate())  AND YEAR(tp.date) < Year(curDate());

SqlFiddle 演示

于 2012-11-10T17:03:09.687 回答
0

这是一个没有连接的版本,只有一个子选择。

SELECT user_id
FROM (
    SELECT user_id,
           MAX(date) AS last_interview,
           COUNT(int_id) AS interviews
    FROM tbl_interviews
    GROUP BY user_id) AS t
WHERE YEAR(last_interview) = 2012 AND interviews > 1

您可以按分组tbl_interviewsuser_id计算每个用户的采访次数,然后筛选出接受过一次以上采访的用户(除了今年接受采访外)。根据您的具体需求,这个主题有很多变化,所以如果需要调整,请告诉我。

例如,这也应该有效。

SELECT user_id
FROM (
    SELECT user_id,
           BIT_OR(YEAR(date) = 2012) AS this_year,
           BIT_OR(YEAR(date) < 2012) AS other_year
    FROM tbl_interviews
    GROUP BY user_id) AS t
WHERE this_year AND other_year
于 2012-11-10T14:49:16.797 回答