# 除了使用相关查询来解决以下问题之外，还有更有效的方法吗？

[英]Is there a more efficient approach other than using a co-related query for solving the below problem?

• `product`
• `product_manufacturer`
• `product_manufacturer_warranties`

product 表与 product_manufacturer 具有一对一的映射关系，product_id 存储在 product_manufacturer 表中。 product_manufactuer 表与 product_manufacturer_warranties 表具有一对多映射。

``````select product.*, pm.web_id,
(   SELECT count(*)
FROM product_manufacturer_warranty pmw
WHERE pm.web_id = pmw.product_manufacturer_id)
AS total_warranties
from product
left join product_manufacturer pm on product.web_id = pm.product_id
``````

``````select product.*,
pm.web_id,
pmw.total_warranties
from product
left join product_manufacturer pm on product.web_id = pm.product_id
left join (
SELECT product_manufacturer_id, count(*) as total_warranties
FROM product_manufacturer_warranty pmw
group by product_manufacturer_id
) as pmw on pm.web_id = pmw.product_manufacturer_id)
``````

``````SELECT p.*
, m.product_id IS NOT NULL AS has_maufacturer
, EXISTS (
SELECT FROM product_manufacturer_warranty w
WHERE  w.product_manufacturer_id = m.web_id
) AS has_warranties
FROM  (
SELECT *
FROM   product
WHERE  product_id > \$max_product_id_of_last_page
-- more filters here?
ORDER  BY product_id
LIMIT  \$page_size
) p
LEFT   JOIN product_manufacturer m ON p.web_id = m.product_id
``````

product 表中的所有列和其他两个列，可用于确定`product``product_manufacturer`以及`product_manufacturer``product_manufactuer_warranties`是否存在有效连接。

• 子查询`p`中第 select 个感兴趣的产品
• 然后左连接到`product_manufacturer` 不能乘行，定义为一对一关系！
• 然后使用`EXISTS`检查是否存在。 如果可以有很多相关行，成本会大大降低。 看：

``````SELECT p.*
, m.product_id IS NOT NULL AS has_maufacturer
, EXISTS (
SELECT FROM product_manufacturer_warranty w
WHERE  w.product_manufacturer_id = m.web_id
) AS has_warranties
FROM  (
SELECT *
FROM   product
WHERE  product_id < \$min_product_id_of_last_page
-- more filters here?
ORDER  BY product_id DESC
LIMIT  \$page_size
) p
LEFT   JOIN product_manufacturer m ON p.web_id = m.product_id
ORDER  BY product_id;
``````