开发者

SQL select count two conditions

开发者 https://www.devze.com 2023-03-31 13:03 出处:网络
I am working on an online form. Before a user fills in th开发者_如何学Cis form, he is asked to select the type of form and the year of the form. These values are placed in $formType and $year respecti

I am working on an online form. Before a user fills in th开发者_如何学Cis form, he is asked to select the type of form and the year of the form. These values are placed in $formType and $year respectively.

I would like to prevent a user from submitting the same form twice ie if user attempts to submit form A for year 2011, and there already exists one in the database, then he is prevented from doing so.

Thus i need a SELECT COUNT function with two conditions, obtained from php variables. So far, I have managed to do this in SQL but only when using one condition, as follows:

SELECT COUNT(`formType`)
    FROM `table1`
    WHERE `formType` = '$formType' ;

However, when i tried to filter both conditions, it didn't work. The code is below:

SELECT COUNT(*)
    FROM (
    SELECT DISTINCT 'year', 'formType' 
    FROM `table1`
    WHERE `year` = '$year' AND 'formType' = '$formType')

Any ideas? Much appreciated


Why do you think you need a subquery? Following should do

SELECT COUNT(*)
    FROM `table1`
    WHERE `year` = '$year' AND `formType` = '$formType'

You probably want to allow one formtype per year per user, so you want to add third condition into query, something like AND userID = xx (unless you have one table per user).


Use 'or' instead of 'and'

select count (*) 
from table1
where (year = $year) or (formtype = $formtype)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号