[英]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. 我想使用数组中的数据来添加列并在MySql表上进行联接。
Let's say, on one hand, we have an array ($relevance): 假设,一方面,我们有一个数组($ 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: 现在,我想从products
表中选择数据,并根据它们的product_id
它们与$relevance
起来,以获得类似以下内容:
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: 换句话说,如何使用来自MySql数据库和一个数组的数据进行LEFT JOIN SELECT,该数组将“表示”如下所示:
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: 纯sql解决方案,尽管对于大型记录集而言效率不高:
$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. 好了,您可以使另一个表相关,然后就可以使用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. 但是,如果您删除某些产品并且这些ID的顺序不正确,则此代码可能会失败,例如:1、2、5、6、7、10。 I recommend you to use another table. 我建议您使用另一个表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.