mysql 获取结果行数,从“ mysql_query”查询结果中计算行数

  • Post author:
  • Post category:mysql


If I have this:

$results = mysql_query(“SELECT * FROM table_name WHERE id=$id”);

is there then any way to check how many rows which have a field-value of “Private” or “Company” ?

I need to show the user how many “Private” and “Company” records where found, without making another query. (There is a column called ‘ad_type’ which contains either “private” or “company”)

I already know the mysql_num_rows for counting all rows!

EDIT:

There are 500thousand records! So maybe an iteration through the result is slow, what do you think?

Thanks for all help 🙂

解决方案

The above answers are great and all, but the currently checked answer will work very inefficiently should you be dealing with a large amount of data

Example of the above answer (via Gal)

$results = mysql_query(“SELECT *,(SELECT COUNT(*) FROM table_name WHERE column=$value) count FROM table_name WHERE id=$id”);

It’s good and all, and it returns what you need but the obvious design flaw is that making your SQL server return the results then re-return them and look at just the count is very inefficient for large amounts of data.

Simply do this:

$results = mysql_query(“SELECT * FROM table_name WHERE column=$value”);

$num_rows = mysql_num_rows($result);

It will yield the same results and be much more efficient in the long run, additionally for larger amounts of data.