用if和count查询

时间:2013-10-19 22:07:22

标签: php mysql

尝试添加if条件以执行以下操作

1-根据用户之前选择的数据选择数据

2-根据所有用户选择的数据时间选择数据

3-设置所有用户可以选择数据的最大次数

这是我当前的代码,因为你可以看到我做出的第一个条件并且它工作正常

$sql=mysql_query(

"SELECT  courseid,coursename
FROM newcourses 
where (courseid not in (select courseid from applicants)
)"

);

例如: 如果我有包含这些行的表新课程

courseid   coursename         max applicant
1          English standard   3
2          English advance    2
3          Spanish            4

表申请人有这些行

id name  courseid
1  me    1
2  jon   1
3  jake  2
4  sara  2
5  joe   3

所以怎么做

4 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT  n.courseid, n.coursename
FROM newcourses n
LEFT JOIN applicants a ON n.courseid = a.courseid
GROUP BY n.courseid, n.coursename
HAVING count(a.id) <=1;

这将获得所有没有申请人的课程和拥有一个申请人的课程。 并且它不会使用必须为每个选定的记录运行一次的子查询,因此您也可以获得性能。

这在新课程和申请人表格之间使用LEFT JOIN。这显示了在申请人表中有记录的新课程的任何元素,但也显示了申请人表格中没有的那些(这是使用LEFT JOIN的原因)。

sqlfiddle demo

如果您想单独检查它们,您可以这样做:

要获得没有申请者的课程:

SELECT  n.courseid, n.coursename
FROM newcourses n
LEFT JOIN applicants a ON n.courseid = a.courseid
GROUP BY n.courseid, n.coursename
HAVING count(a.id) = 0;

排除有两名申请人的课程:

SELECT  n.courseid, n.coursename
FROM newcourses n
LEFT JOIN applicants a ON n.courseid = a.courseid
GROUP BY n.courseid, n.coursename
HAVING count(a.id) != 2;

如果您不能超过两个,则可以将!=更改为<


如果您最终向具有最大申请人数的新课程添加新列,则无法将其添加到外部HAVING COUNT中,因此您必须执行子查询:

SELECT  n.courseid, n.coursename
FROM newcourses n
LEFT JOIN applicants a ON n.courseid = a.courseid
WHERE n.maxApplicants >= (SELECT count(*) 
                          FROM applicants ap WHERE ap.courseid = n.courseid)
GROUP BY n.courseid, n.coursename

答案 1 :(得分:0)

这是你想要做的吗?

$sql = mysql_query( 

   "SELECT  courseid,coursename
   FROM newcourses 
   WHERE (courseid NOT IN (SELECT courseid FROM applicants GROUP BY courseid HAVING( COUNT( courseid ) > 1)))
   "
);

“HAVING(COUNT(courseid)&gt; 1))”将返回表“申请人”的倍数出现值。

答案 2 :(得分:-1)

SELECT  courseid,coursename
FROM newcourses 
where courseid not in (select courseid from applicants GROUP BY courseid HAVING COUNT(courseid)=2)

如果您想忽略三元组或更多三元组的课程,请使用HAVING COUNT(courseid)>1

答案 3 :(得分:-1)

您必须使用GROUP BY - HAVING等过滤器在子查询中包含所有负行。

SELECT courseid, coursename
FROM newcourses 
WHERE courseid NOT IN (SELECT courseid FROM applicants GROUP BY courseid HAVING COUNT(courseid) > 1)

易于阅读:

SELECT courseid, coursename
FROM newcourses 
WHERE courseid IN (SELECT courseid FROM applicants GROUP BY courseid HAVING COUNT(courseid) = 1)