简体   繁体   English

显示来自MySQL数据库的结果数

[英]Displaying number of results from a MySQL db

I have a classifieds website, and it is using MySQL as a database. 我有一个分类广告网站,它使用MySQL作为数据库。

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 . 问题:广告有两种类型: PrivateCompany The user may specify which to display, or both, so thats three options. 用户可以指定显示哪个,或同时显示两个,因此这是three选项。

On the website, after displaying the search results, I want to show the user THREE tabs: All ads , Private ads , Company ads . 在网站上,显示搜索结果后,我要向用户显示THREE标签: All adsPrivate adsCompany ads

I have a field in every record in MySQL which contains the value of either Private or Company . 我在MySQL的每条记录中都有一个field ,其中包含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 . 我知道一种显示私人广告,公司广告和TOTAL广告数量的方法,但是它需要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 : 您可以使用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. 一次查询所有数据并将其传递给PHP。 Once you have it in PHP set up three separate loops.. Eg: 在PHP中使用它后,请设置三个单独的循环。例如:

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. 如果您只是想要计数,请在选择计数时使用GROUP BY子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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