mysql优化一个类别中的广告数量

  • 本文关键字:优化 一个 mysql php mysql
  • 更新时间 :
  • 英文 :


我有一个个人广告网站。

第一个问题:我有两个表,categoryads

Category表(id为主键(

| id  | type        | subtype   | pos    |
+-----+-------------+-----------+--------+
| 1   | sell        |           | 1      |
| 2   | jobs        |           | 2      |
| 3   | dating      |           | 3      |
| 4   | dating      | boys      | 1      |
| 5   | dating      | girls     | 2      |
| 6   | sell        | cars      | 1      |
| 7   | jobs        | teacher   | 1      |

Ads表(id是主键(-这个表有很多广告

| id  | title       | type      | subtype|
+-----+-------------+-----------+--------+
| 1   | some text   | sell      | cars   |
| 2   | some text   | dating    | girls  |
| 3   | some text   | dating    | boys   |

我想阅读所有类别类型,并获得该类型的广告总数,我还需要获得子类型。

我页面上的输出将是

Sell (1 ads)
Cars
Jobs (0 ads)
Teacher
Dating (2 ads)
Boys
Girls

我目前正在做的是使用php和mysql进行3次查询,其中第一次返回类别类型是select where subtype=",第二次统计这些类别中现有的广告,第三次为每种类型提供子类型,我想优化mysql,减少查询数量,更快,即使这意味着更改表和添加更多索引

选择查询:

select * 
from category  
where subtype = '' 
order by pos desc

计数一种类型的广告数量:

select type 
from ads 
where type = '$type_name'

选择子类型:

select * 
from category  
where type = '$type_name' 
and subtype !='' 
order by pos

您可以使用此

SELECT c.*,a.c_ads
FROM
category c LEFT JOIN ( SELECT COUNt(type) c_ads,type FROM ads GROUP BY type) a
ON c.type = a.type
ORDER BY c.type,c.pos DESC
id|type|subtype|pos|c_ads-:|:-----|:------|--:|----:3|约会||3|25|约会|女孩|2|24|约会|男孩|1|22|jobs||2|null5|jobs|教师|1|null1|sell||1|15|sell|cars|1|1

请参阅fiddle

当你在php中逐行检查数据时,如果类型发生变化,那么你可以使用列c_ads来显示($row{'c_ads']ads(和行['type']来显示类别的文本

如果行['type']没有更改,您可以在行['subtype']中找到行['type']的子类别

最新更新