简体   繁体   中英

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:

$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".

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.

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.

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. But what's odd about your question, is why you have an "in" at all. 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

)';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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