1

Look at my table below, I am trying to count the A in the table. A will only appear in one row, but sometime will be in the first column, sometime will be in other column, so I use OR, but it echo a number larger than 3, I only have 3 A, why? How can I only count 3 A?

"SELECT COUNT(*) FROM $table WHERE first='A' OR second='A' OR third='A' AND number <= 7"

id  first  second third  number
1     A      C      B      3
2     C      d      F      5
3     A      c      b      6
4     B      A      c      7
5
  • 4
    It sounds like you want WHERE (first='A' OR second='A' OR third='A') AND number <= 7 Commented Jan 29, 2016 at 6:05
  • Or how about 'A' IN (first, second, third)? Commented Jan 29, 2016 at 6:09
  • @shmosel I think parameter in bracket must be a value not the column name. Correct me if i am wrong. Commented Jan 29, 2016 at 6:12
  • @Mr.Engineer, you are indeed. Commented Jan 29, 2016 at 6:13
  • Can it be possible that A comes twice or more in single row? Commented Jan 29, 2016 at 6:37

4 Answers 4

1
"select count(*) 
 from $table 
 where (first = 'A' or second = 'A' or third = 'A') 
 and number <= 7";
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT 
(select count(*) from tablename where first LIKE '%A' and number<=7)
+
(select count(*) from tablename where second LIKE '%A' and number<=7)
+
(select count(*) from tablename  where third LIKE '%A' and number<=7);

try this code ,am sure you wil definitely get the right count

Comments

0

You are going right just need to do two things:

  • Combine OR condition into brackets ()
  • Add backticks for MYSQL Keywords (second is a MYSQL Keywords)

Modified Query:

"SELECT COUNT(*) FROM $table 
WHERE (`first` = 'A' OR `second` = 'A' OR `third` = 'A') 
AND `number` <= 7"

Comments

0

Try this if A occurs more than on single row:

select sum(if(first = 'A',1,0)+if(second = 'A',1,0)+if(third = 'A',1,0)) as count
from $table where number <= 7;

SQL Fiddle:http://sqlfiddle.com/#!9/f34a8/3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.