1

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

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

Comments

0

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, e.g.: 1,2,5,6,7,10. I recommend you to use another table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.