将一个查询的结果传递给另一个查询,然后合并这两个查询的结果

时间:2015-07-13 09:39:08

标签: mysql sql

我有以下查询:

SELECT name as String
     , COUNT(*) Total
     , SUM(product = 1) Product
           FROM String
                WHERE language = 1
           GROUP 
                BY name
           ORDER
                BY total desc
           LIMIT 10

此查询的目的是根据字符串在String表中的出现情况报告TOP-10,并报告它们在特定产品中的出现(id = 1)。

我想在结果中添加另一列,它将计算每个字符串在另一个字符串中间出现的次数。为此,我有一个由全文索引编制索引的表Copy

我的问题是弄清楚如何将String列的值从结果传递给此查询:

SELECT COUNT(name) as inAll
    FROM Copy c
        WHERE MATCH(c.name) AGAINST (/*String*/)

是否可以通过一个SQL查询来实现此结果?

Before:                   After:

String Total Product      String Total Product inAll
+-----+-----+------+      +-----+-----+-------+-----+
|blah | 52  |  12  |      |blah | 52  |  12   | 96  |
|bleh | 23  |  14  |      |bleh | 23  |  14   | 56  |
|bloh | 14  |  11  |      |bloh | 14  |  11   | 34  |
+-----+-----+------+      +-----+-----+-------+-----+

感谢。

修改

我的架构:

CREATE TABLE Language (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(30) NOT NULL,
    `code` VARCHAR(10) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci; 

CREATE TABLE Product (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;

CREATE TABLE String (
    `id` INT NOT NULL AUTO_INCREMENT,
    `label` VARCHAR(200),
    `name` TEXT(500) NOT NULL,
    `language` INT NOT NULL,
    `product` INT NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci;

CREATE TABLE Copy (
    `id` INT NOT NULL,
    `name` TEXT(500) NOT NULL,
    PRIMARY KEY (`id`),
    FULLTEXT(name)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci;

INSERTDELETEUPDATE触发。

1 个答案:

答案 0 :(得分:1)

您可以尝试加入StringCopy表格:

SELECT COUNT(*) AS inAll, t.String AS String, t.Total AS Total, t.Product AS Product
FROM Copy c
INNER JOIN
(
    SELECT name AS String, COUNT(*) Total, SUM(product = 1) Product
    FROM String
    WHERE language = 1
    GROUP BY name
    ORDER BY COUNT(*) desc
    LIMIT 10
) t
ON c.name = t.name