如何从" IN"更改MYSQL查询到" INNER JOIN"?

时间:2015-09-04 19:49:48

标签: php mysql joomla

我有这个代码来搜索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
)';

我想更改上面的搜索查询,使用" IN"操作员到" INNER JOIN"。

知道无论如何我都无法改变任何数据库结构,只需修改上面的代码即可。

3 个答案:

答案 0 :(得分:0)

我需要查看完整的查询,但猜测它将是:

$users = array();
$user[] = array('name' => "1", 'players' => "players");
$user[] = array('name' => "2", 'players' => "players");
$user[] = array('name' => "3", 'players' => "players");
$user[] = array('name' => "1", 'players' => "players"); // this won't be included
$user[] = array('name' => "4", 'players' => "players");
$user[] = array('name' => "5", 'players' => "players");

foreach ($user as $u) {
    if(!in_array($u, $users)) $users[] = $u;
}

print_r($users);

其中$ table是第一个表的表名。

答案 1 :(得分:0)

只需将子查询移动到内联视图别名,然后加入键。

并且看起来你可以在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

答案 2 :(得分:0)

您需要发布查询的其余部分,因为未显示能力p。但是你的问题有多奇怪,这就是为什么你有一个“in”。我想你只需要做以下事情:

  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

)';