mySQL: Subquery to array?(mySQL:数组的子查询?)
问题描述
我正在处理一个稍微复杂的(至少对我而言)mySQL 查询,其中包含一个子查询,但说实话并不好.
I am working on a slight complex (at least for me) mySQL query containing a subquery and it isn't going to well to be honest.
SELECT `products`.`id`, `product`.`price`, 
  ( SELECT `value` FROM (`productValues`) 
    WHERE `productValues`.`product` = 'product.id'
  ) as values 
FROM (`products`) WHERE`product`.`active` = 1
目前的结果是这样的:
Array
(
    [0] => Array
        (
            [id] => 1
            [active] => 1
            [price] => 1000
            [values] => 
        )
)
我想要的是 values 元素也成为一个数组,其中包含 Values 表中匹配的所有元素(WHERE productValues.product = product.id).
What I want is the values element to also  become an array with all elements in the Values table which matches (WHERE productValues.product = product.id).
我做错了什么?
推荐答案
SELECT p.id, p.price, pv.`value`
FROM products p
  JOIN  productValues pv
  ON p.product_id=pv.product
WHERE p.active = 1
ORDER BY p.id;
为每个 pv.value 提供一个包含一行的表(顺便说一句,不建议使用保留字如 'value').按 p.id 对输出进行排序可确保特定产品的所有行都在一起.因此,在应用程序层中,循环遍历您的行,每次 p.id 更改时更改产品.
gives a table with one row for each pv.value (BTW, using reserved words like 'value' is not recommended). Ordering the output by p.id ensures that all the rows for a particular product are together. So, in the application layer, loop through your rows, changing product each time the p.id changes.
$old_id=NULL;
$datastructure=array();
while($arr=$result->fetch_assoc()){
  if($arr['id']!=$old_id){
    $datastructure[$arr['id']][price]=$arr['price'];
    $old_id=$arr['id'];
  }
  $datastructure[$arr['id']]['values'][]=$arr['value'];
}
我给出的结构可能比您要求的结构更灵活,因为它允许您通过数组键访问特定产品.
The structure I've given is perhaps more flexible than the one you asked for in that it allows you to access a particular product through the array key.
这篇关于mySQL:数组的子查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:mySQL:数组的子查询?
				
        
 
            
        基础教程推荐
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
 - MySQL 5.7参照时间戳生成日期列 2022-01-01
 - 带更新的 sqlite CTE 2022-01-01
 - 带有WHERE子句的LAG()函数 2022-01-01
 - CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
 - MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
 - while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
 - ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
 - 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
 - 从字符串 TSQL 中获取数字 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				