0

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

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

2-根据所有用户选择数据的次数来选择数据

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

这是我当前的代码,您可以看到我在第一个条件下所做的一切,并且工作正常

$sql=mysql_query(

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

);

例如:如果我有包含这些行的表 newcourses

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

4 回答 4

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;

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

这在 newcourses 和申请人表之间使用了 LEFT JOIN。这显示了在申请者表中有记录的 newcourses 的任何元素,但也显示了不在申请者表中的元素(这就是使用 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
于 2013-10-19T22:34:03.390 回答
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) > 1))" 将返回表 "applicants" 的多次出现值。

于 2013-10-19T22:58:11.023 回答
-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)
于 2013-10-19T22:36:39.607 回答
-1
SELECT  courseid,coursename
FROM newcourses 
where courseid not in (select courseid from applicants GROUP BY courseid HAVING COUNT(courseid)=2)

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

于 2013-10-19T22:13:48.937 回答