1

我做了一个使用 group by 的声明。现在,我需要知道每条记录的详细信息,但我需要在一个语句中执行此操作。

例如:我进行了以下查询来查询以_1相同结尾和共享的文件number

SELECT number, COUNT(*) AS sum domains FROM table
WHERE file LIKE '%_1' GROUP BY number HAVING sum domains> 1

所以,如果我有下表:

domain      |   file      | Number 
------------------------------------     
aaa.com     | aaa.com_1   | 111
bbb.com     | bbb.com_1   | 222
ccc.com     | ccc.com_2   | 111
ddd.com     | ddd.com_1   | 222
eee.com     | eee.com_1   | 333
qqq.com     | qqq.com_1   | 333

查询的结果是(number被多个共享的那个和以这个数字结尾并共享这个数字file的(s)的计数):file_1

number | sum domains
------------------------
222    | 2
333    | 2

我需要做的是打印出文件名。我需要:

number | file
------------------------
222    | bbb.com_1 
222    | ddd.com_1
333    | eee.com_1
333    | qqq.com_1

我怎么能这样做,因为group by子句不允许我打印file(s) ?

4

1 回答 1

1

您可以JOIN将查询作为子查询返回到主表,以获取原始行和文件名:

SELECT 
  main.number, 
  main.file
FROM 
  table AS main
  /* Joined against your query as a derived table */
  INNER JOIN (
    SELECT number, COUNT(*) AS sum domains 
    FROM table
    WHERE RIGHT(file, 2) = '_1' 
    GROUP BY number 
    HAVING sum domains > 1
    /* Matching `number` against the main table, and limiting to rows with _1 */
  ) as subq ON main.number = subq.number AND RIGHT(main.file, 2) = '_1'

http://sqlfiddle.com/#!2/cb05b/6

请注意,我已将您的替换LIKE '%_1'RIGHT(file, 2) = '_1'. 不过,如果没有基准,很难说哪个会更快。

于 2012-12-16T01:26:46.163 回答