生成按user_id分组的订单表,该表汇总了产品数量

时间:2018-06-09 12:18:01

标签: php mysql woocommerce

我有一个庞大的mysql表(在woocommerce中),人们可以多次购买物品。我想做的是有一个表动态生成我选择我想要查询的产品(如果可能的话,从php下拉菜单中),并对user_id购买的产品的数量进行分组。我发现了this代码,但无法生成我想要的表格。这是我目前的测试代码,试图让它工作,但没有生成表格;

<?php 
if (!is_user_logged_in() || !current_user_can('manage_options')) wp_die('This page is private.');

$con=mysqli_connect("ip","user","pass","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,
"select p.user_id,
       max( CASE WHEN pm.meta_key = '_billing_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_first_name,
       max( CASE WHEN pm.meta_key = '_billing_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_last_name,
       max( CASE WHEN pm.meta_key = '_billing_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_1,
       group_concat(distinct oi.order_item_name separator '|' ) as order_items
from wp_posts p join
    wp_postsmeta pm
    on p.ID = pm.post_id join
    wp_woocommerce_order_items oi
where p.post_type = 'shop_order' and
      p.post_status = 'wc-completed' and
      oi.order_item_name = 'Product Name'
group p.user_id");
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr style='font-size: 0.665em'>";
echo "<td>"  . $row['billing_first_name'] . "</td>";
echo "<td>" . $row['_billing_last_name'] . "</td>";
echo "<td>" . $row['billing_address_1'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>

我的最终目标是使用下拉菜单根据产品ID选择有问题的产品,这样我就可以看到每个用户购买了所查询产品的数量(仅按上述代码完成订单);

user ID | Product | quantity | billing address 
23      | chair   | 4        | 22 Bank street
42      | chair   | 12       | 123 Smith Road
88      | chair   | 5        | 3 Parker avenue

1 个答案:

答案 0 :(得分:0)

我不确定你为什么在select中使用子查询。您还要选择不需要/不需要的列。

这样做你想要的吗?

select p.user_id,
       max( CASE WHEN pm.meta_key = '_billing_first_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_first_name,
       max( CASE WHEN pm.meta_key = '_billing_last_name' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_last_name,
       max( CASE WHEN pm.meta_key = '_billing_address_1' and p.ID = pm.post_id THEN pm.meta_value END ) as _billing_address_1,
       group_concat(distinct oi.order_item_name separator '|' ) as order_items
from wp_posts p join
     wp_postmeta pm
     on p.ID = pm.post_id join
     wp_woocommerce_order_items oi
     on p.ID = oi.order_id
where p.post_type = 'shop_order' and
      p.post_status = 'wc-completed' and
      oi.order_item_name = 'Product Name'
group by p.user_id;

我不得不推测某些列的来源,因为你的问题不明确。

相关问题