简体   繁体   English

如何将 MYSQL 查询从“IN”更改为“INNER JOIN”?

[英]How to change a MYSQL query from "IN" to "INNER JOIN"?

I have this code to search for a matching result in a MYSQL database:我有以下代码在 MYSQL 数据库中搜索匹配结果:

$where[] = 'p.id IN (
    SELECT adcfvc.advert_id
      FROM #__koparent_advert_specific_fields_values AS adcfvc
     WHERE adcfvc.advert_id = p.id
       AND adcfvc.field_name = ' . $db->Quote($sf_key) . '
       AND ' . $db->Quote(JString::strtolower($sf_value)) . ' = adcfvc.field_value
)';

I want to change the above search query from using the "IN" operator to "INNER JOIN".我想将上述搜索查询从使用“IN”运算符更改为“INNER JOIN”。

Knowing that I cannot change any of the database structure in anyway, just modify the above code.知道无论如何我都无法更改任何数据库结构,只需修改上面的代码即可。

I need to see the full query, but at a guess it is going to be:我需要查看完整的查询,但我猜测它将是:

LEFT JOIN adcfvc ON adcfvc.advert_id = $table.id

Where $table is the tablename of the first table.其中 $table 是第一个表的表名。

Simply move the subquery to an inline view alias it and join on the keys.只需将子查询移动到内联视图别名并加入键即可。

and it appears you could eliminate the correlated sub-query in the where clause.看来您可以消除 where 子句中的相关子查询。

SELECT ...
FROM ...
LEFT JOIN (
    SELECT adcfvc.advert_id
      FROM #__koparent_advert_specific_fields_values AS adcfvc
     WHERE adcfvc.field_name = ' . $db->Quote($sf_key) . '
       AND ' . $db->Quote(JString::strtolower($sf_value)) . ' =
           adcfvc.field_value) B 
  on B.advert_Id = p.id

You'll need to post the rest of the query, because the able p is not shown.您需要发布查询的其余部分,因为未显示能够 p 。 But what's odd about your question, is why you have an "in" at all.但是你的问题很奇怪,就是为什么你有一个“in”。 I think you just need to do the following:我认为您只需要执行以下操作:

  FROM #__koparent_advert_specific_fields_values AS adcfvc, whatever_table as p
 WHERE adcfvc.advert_id = p.id
   AND adcfvc.field_name = ' . $db->Quote($sf_key) . '
   AND ' . $db->Quote(JString::strtolower($sf_value)) . ' = adcfvc.field_value

)'; )';

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

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