简体   繁体   English

MySQL对多个表计数是唯一的

[英]MySQL count unique over multiple tables

I have two tables: 我有两个表:

products            product_eans
+--+-----------+    +----------+-------------+
|id|name       |    |product_id|ean          |
+--+-----------+    +----------+-------------+
| 1|hello world|    |         1|4053804303361|
+--+-----------+    +----------+-------------+
| 2|hello mars |    |         1|4053804304788|
+--+-----------+    +----------+-------------+
                    |         2|4053804304825|
                    +----------+-------------+

I now want to count the (unique) products that has the string 4788 in their name or in one of their EANs. 我现在要计算名称(或其中一个EAN)中包含字符串4788的(独特)产品。 The result in the example would be 1 (one product has an EAN that contains the search string 4788 ) 示例中的结果将为1(一种产品的EAN包含搜索字符串4788

I have managed this with 我已经用

SELECT
        COUNT(DISTINCT products.id) AS count
    FROM
        products
    WHERE
        products.name LIKE "%4788%" OR 
        (SELECT
            GROUP_CONCAT(ean)
        FROM
            product_eans
        WHERE
            product_id = product.id) LIKE "%4788%"`

but it's incredible slow with thousands of rows in both tables. 但是两个表中都有成千上万的行, 速度实在令人难以置信。

What is the most efficient way for a query like this? 这样的查询最有效的方法是什么?

Using "double-ended wildcards" is never going to be fast because you won't get use of indexing so the tables will be scanned. 使用“双头通配符”永远不会很快,因为您不会使用索引,因此将扫描表。 An inner join is probably the most efficient 内部联接可能是最有效的

SELECT COUNT(DISTINCT e.products_id)
FROM product_eans e
inner join products p on e.products_id = p.id
WHERE e.ean LIKE '%4788%'
OR p.name LIKE '%4788%'

but one other possibility is to avoid the OR in tha wheer clause by using a union query like this: 但另一种可能性是通过使用像这样的联合查询来避免tha wheer子句中的OR:

  SELECT
        COUNT(*)
  FROM (
        SELECT
              product_id
        FROM product_eans
        WHERE ean LIKE '%4788%'
        UNION
        SELECT
              id
        FROM products
        WHERE name LIKE '%4788%'
  ) d

After being inspired by Used_By_Already, I came across a simple idea: 受到Used_By_Already的启发后,我遇到了一个简单的想法:

SELECT
    COUNT(DISTINCT products.id) AS count
FROM
    products
WHERE
    products.name LIKE "%4788%" OR
    products.id in (SELECT product_id FROM product_eans WHERE ean "%4788%")

It's super fast now. 现在超级快。 So thanks to Used_By_Already. 因此,感谢Used_By_Already。

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

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