我创建了一个页面,我想在其中按年份和月份对分组进行分组,然后将用户按该月份分组 并将商品归类到购买商品的用户。 所以看起来像这样
january 2018
user 1 -> item 1
-> item 5
-> item 7
user 4 -> item 2
-> item 1
user 7 -> item 6
以此类推。
我觉得我已经接近了,也许只是想念一些简单的东西,这是我的代码
$sql = '
SELECT
i.*, o.*, oi.*, u.*, YEAR(o.sold_date) sold_date_Y, MONTH(o.sold_date) sold_date_M, u.name, COUNT(o.user_id)
FROM items i
INNER JOIN order_items oi ON i.id = oi.item_id
INNER JOIN orders o ON o.id = oi.order_id
INNER JOIN users u ON u.id = o.user_id
GROUP BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.title
ORDER BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.title
';
$result = mysqli_query($con, $sql);
$savYM = '';
while($row = mysqli_fetch_array($result)){
$curYM = $row['sold_date_Y'].'-'.$row['sold_date_M'];
if($curYM != $savYM){
echo '<br/>'. date('F, Y', strtotime($curYM)) .'<br/>';
}
echo $row['name'].'<br/>';
echo $row['title'].'<br/>';
$savYM = $curYM;
}
这会正确输出50%,所有内容都按月和年分组,但是之后我得到了重复的用户,因此最终看起来像这样
january 2018
user 1 -> item 1
user 7 -> item 6
user 1 -> item 5
user 4 -> item 2
user 1 -> item 7
user 4 -> item 1