简体   繁体   中英

Use array as table in MySql JOIN

I would like to use data from an array to add a column and make a join on a MySql table.

Let's say, on one hand, we have an array ($relevance):

$relevance = array(
  array('product_id' => 1, 'relevance' => 2),
  array('product_id' => 2, 'relevance' => 5),
  array('product_id' => 3, 'relevance' => 1),
);

And on the other hand, we have this table (products):

product_id  | product_name
--------------------------
1           | Product 1
2           | Product 2
3           | Product 3

Now, I want to select data from the products table and joining them with $relevance based on their product_id in order to get something like this:

product_id  | product_name  | relevance
---------------------------------------
1           | Product 1     | 2
2           | Product 2     | 5
3           | Product 3     | 1

In other words, how can I make a SELECT with LEFT JOIN using data from both the MySql database and an array which would "mean" something like this:

SELECT `p`.*, `{{$relevance}}`.* FROM `products` AS `p`
LEFT JOIN `{{$relevance}}`
ON p.product_id = {{$relevance}}.product_id

pure sql solution, not efficient though for big recordsets:

$relevances = array()

foreach ($relevance as $v){
    $relevances[] = "SELECT {$v['product_id']} as product_id, {$v['relevance']} as relevance"
}

$sql = implode(' UNION ', $relevances);

$sql = "SELECT p.product_id, p.product_name, r.relevance 
FROM products p 
JOIN ($sql) r ON p.product_id=r.product_id";

Well, you can make another table relevance and then you could just use JOIN. Or you can use loop to get those data. Something like

$relevance = array(
    array(1, 'relevance' => 2),
    array(2, 'relevance' => 5),
    array(3, 'relevance' => 1),
);

$q = mysql_query("SELECT * FROM products")
while($r = mysql_fetch_assoc($q))
{
   $productRelevance = $relevance[$r['prod_id']-1];
}

Hoewever this code may fail if you delete some product and those ids wouldn' be in order, eg: 1,2,5,6,7,10. I recommend you to use another table.

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