简体   繁体   中英

Count how many times a value appears in sql query using php

I have created a database and website that will be used by football managers to select their team etc. Once a match has been completed events will be stored in the match_players table. Such events are Goal, Yellow Card, Red Card etc. I have no problem getting this information into php from SQL db.

I need to add up how many times a Goal appears (a '1' is placed in the SQL table) and for what team so that a final score can be displayed. So, for example, if Team A has 1 goal and Team B has 2 then I need to display that. I am trying to count the amount of times that a Goal is registered in the table. Any help will be greatly appreciated.

You can use MYSQL SUM

select SUM(Goal) from match_players where Team="A"

Or you can get the same for all teams by

select Team,SUM(Goal) from match_players group by Team

Why don't you demand this sum to SQL directly?

SELECT SUM(goals)
FROM match_table
WHERE team = 'Barcellona'

This should be much faster also than elaborate all data at "php-level"

If you want this detail for all teams

SELECT team,SUM(goals)
FROM match_table
GROUP BY team

Well if you store a 1 each time a goal is scored, your table looks like this:

TeamID  goal
   1     1
   2     1
   1     1
   3     1
   2     1
   2     1
   1     1

So you just want a count of how many times a team appears in that table:

select TeamID, count(*) from table group by TeamID

Will give you

 TeamID | count(*)
     1  |  3
     2  |  3
     3  |  1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM