开发者

Displaying number of results from a MySQL db

I have a classifieds website, and it is using MySQL as a database.

My goal is to show the number of private, company and total ads in the db with the search-term entered in a text-input inside the form!

The Problem: There are two types of ads: Private, and Company. The user may specify which to display, or both, so thats three options.

On the website, after displaying the search results, I want to show the user THREE tabs: All ads, Private ads, Company ads.

I have a field in every record in MySQL which contains the value of either Private or Company.

I know of a way to display the number of private ads, company ads and TOTAL ads but it requires multiple queries.

For example, if the user CHECKS开发者_如何学编程 the PRIVATE ONLY check-box then only private ads are searched, but I won't know how many company ads there are until I make a new query, where I search also for company ads. Then add them, and I have also the total nr of ads.

Just wonder if you know of a good way, to maybe get rid of the extra query?

Thanks


You could use a ROLLUP:

SELECT
    IFNULL( field , 'All ads' ) AS 'Type',
    COUNT( * )
FROM
    `table`
GROUP BY
    field
WITH ROLLUP

So with four Company and one Private ad you would see:

Type       COUNT( * )
Company    4
Private    1
All ads    5


SELECT field , COUNT( id ) 
FROM db
GROUP BY field;


Query all of the data at once and pass it off to PHP. Once you have it in PHP set up three separate loops.. Eg:

foreach($data AS $row)
{
    if($row['type'] == 'company')
    {
        // LOOP THROUGH COMPANY DATA
    }
}

foreach($data AS $row)
{
    if($row['type'] == 'private')
    {
        // LOOP THROUGH PRIVATE DATA
    }
}

This way you only pull your data set once, but you can surgically show the data you want from the set in each tab separately.

If you are just wanting counts use a GROUP BY clause when you select your counts.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜