在另一个查询中查询,如果另一个查询不存在则返回0并比较2个查询之间的值

时间:2015-09-28 07:16:09

标签: php mysql

我一遍又一遍地搜索,但仍然无法写出真正有用的正确查询! :|

我写了这个,看起来没问题,但它没有用......

select 
  s.surf_id, 
  s.surf_dailyuser, 
  s.surf_url, 
  s.surf_cpc, 
  (if exists(
   select surfed_count from `surfed` where s.surf_id = surfed_site and surfed_date = 'today'
  ) then select surfed_count as surfedcount;
   else select 0 as surfedcount; end if
  )
  from `surfs` s where s.surf_status = 1 and surfedcount < s.surf_dailyuser order by s.surf_rand limit 1

任何建议都将是一个很大的帮助:)

表格就像这样

冲浪

CREATE TABLE IF NOT EXISTS `surfs` (
  `surf_id` int(11) NOT NULL,
  `surf_user` int(11) NOT NULL,
  `surf_title` varchar(128) CHARACTER SET latin1 NOT NULL,
  `surf_url` varchar(500) CHARACTER SET latin1 NOT NULL,
  `surf_dailyuser` int(11) NOT NULL,
  `surf_cpc` int(11) NOT NULL,
  `surf_status` int(11) NOT NULL,
  `surf_date` varchar(32) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

冲浪

CREATE TABLE IF NOT EXISTS `surfed` (
  `surfed_id` int(11) NOT NULL,
  `surfed_code` int(11) NOT NULL,
  `surfed_user` int(11) NOT NULL,
  `surfed_site` int(11) NOT NULL,
  `surfed_count` int(11) NOT NULL,
  `surfed_date` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:0)

您可以使用下面的CASE语句

select 
  s.surf_id, 
  s.surf_dailyuser, 
  s.surf_url, 
  s.surf_cpc, 
  CASE WHEN 
   (select surfed_count from `surfed` where s.surf_id = surfed_site and surfed_date = 'today') = 1 then (select surfed_count as surfedcount)

  ELSE 0 END AS surfedcount
  from `surfs` s where s.surf_status = 1 and surfedcount < s.surf_dailyuser order by s.surf_rand limit 1