【问题标题】:Mysql - Run the nex AND Condition if first one is TRUEMysql - 如果第一个为 TRUE,则运行下一个 AND 条件
【发布时间】:2013-12-26 09:21:24
【问题描述】:

这是我的代码:

SELECT *
FROM (`View_Products_With_Category`)
WHERE `category_id` =  '47'
AND `top_id` =  0
AND (select count(product_id) from Modules where product_id=`View_Products_With_Category`.id)= 0
ORDER BY `order`, `sub_order`, `code` 

此查询从 15.000 条记录中返回 8 行。我的问题是 (select count(product_id) from Modules where product_id=View_Products_With_Category.id)= 0 行工作太慢了。

如果第一个条件为 TRUE,我需要一个语法来让慢行工作。

这可能吗?

【问题讨论】:

  • 是的,有可能,但在您的特定情况下,最好将子查询转换为JOIN

标签: mysql sql select join left-join


【解决方案1】:

您可以使用LEFT JOIN

试试这个:

SELECT V.*
FROM View_Products_With_Category V
LEFT JOIN Modules M ON V.id = M.product_id
WHERE V.category_id =  '47' AND V.top_id =  0 AND M.product_id IS NULL
ORDER BY V.order, V.sub_order, V.code

【讨论】:

    【解决方案2】:

    使用left join 并检查连接是否与is null 一起使用。

    SELECT v.*
    FROM `View_Products_With_Category` v
    LEFT JOIN modules ON m.product_id= v.id
    WHERE v.`category_id` =  '47'
    AND v.`top_id` =  0
    AND m.product_id IS NULL
    ORDER BY v.`order`, v.`sub_order`, v.`code` 
    

    this great explanation of joins

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多