English 中文(简体)
MySQL:返回的田地,该集团没有空洞,效率高
原标题:MySQL: Return grouped fields where the group is not empty, efficiently

在一份发言中,Im试图通过加入另一张桌子把一个桌子组起来。 我只想看到集束灯,因为它们的分组结果并非空洞。

页: 1

SELECT Category.id
FROM Item, Category
WHERE Category.id = Item.categoryId
GROUP BY Category.id
HAVING COUNT(Item.id) > 0

以上询问给我带来了我希望的结果,但这很缓慢,因为它必须计算所有按类别分类的浏览量。

越是有效的方法?

我正试图通过利比里亚国家警察集团,只找回每组一行。 但是,我的尝试却 failed然失败。 我如何能够这样做的想法?

增 编

最佳回答

为此:

SELECT  item.categoryid
FROM    Item
JOIN    Category
ON      Category.id = Item.categoryId
GROUP BY
        item.categoryid
HAVING  COUNT(*) > 0

这与你最初的询问相似,但获得的却是你想要的。

如果你想选择非豁免类别,则:

SELECT  category.id
FROM    category
WHERE   id IN
        (
        SELECT  category_id
        FROM    item
        )

为加快工作,编制<代码>项目(类别_id)索引。

问题回答

如果你不需要的话,消除这一类表格有什么意义?

SELECT Item.categoryId 
FROM Item
GROUP BY Item.categoryId

我不敢肯定你甚至需要“HAVING”条款,因为如果在某个类别中没有任何项目,它就不会产生一个集团。

我认为,这在功能上是等同的(每个类别至少有一个项目),而且应当更快。

SELECT 
  c.id
FROM 
  Category c
WHERE
  EXISTS (
    select 1 from Item i where i.categoryid = c.categoryID
  )

我认为,这只是我的意见,即,正确的做法是把所有问题都算在内。 也许问题在于另一个地方。

这是我用来计算的情况,尽管有大量数据,但这项工作速度快。

SELECT categoryid, COUNT(*) FROM Item GROUP By categoryid

它将给你一个按类别列出的所有项目的斜体。 但NOT将包含空档类别。

然后,对于检索类别信息来说,情况就是如此:

SELECT category.* FROM category
INNER JOIN (SELECT categoryid, COUNT(*) AS n FROM Item GROUP By categoryid) AS item
ON category.id = item.categoryid




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签