通过我的PHP循环时无法获取所有必要的数据

时间:2019-05-31 13:54:06

标签: php mysql

我正在尝试创建一个页面,其中列出所有在不同月份出售商品的用户,但每个用户本可以在该月份的不同日期出售商品。这是什么 我正在努力。

January
user 1
user 4
user 5

February
user 4
user 2
user 3

我设法使它列出了月份,但每月只显示一个用户。例如

January
user 1

February
user 4

这是我的代码

$sql = "SELECT * FROM users INNER JOIN items ON users.id = items.user_id GROUP BY Year(items.sold_date), Month(items.sold_date)";
$result = mysqli_query($con, $sql);

$mnt = "";
while($row = mysqli_fetch_array($result))
{
    if($row['sold_date'] != $mnt)
    {
        echo date('F, Y', strtotime($row['order_date'])); 
        echo "<br/>";
    }

    echo $row['name'];
}

我的用户表

id | name   | lastname        
1  | user 1 | user 1 lastname 
2  | user 2 | user 2 lastname 
3  | user 3 | user 3 lastname 
4  | user 4 | user 4 lastname 
5  | user 5 | user 5 lastname 

我的物品表

id| name   |description         | user_id | sold_date
1 | item 1 | item 1 description | 3       | 2017-01-25
2 | item 2 | item 2 description | 1       | 2017-01-30
3 | item 3 | item 3 description | 5       | 2017-02-14
4 | item 4 | item 4 description | 2       | 2017-05-01
5 | item 5 | item 5 description | 1       | 2018-09-06
6 | item 6 | item 6 description | 4       | 2018-10-23

我希望我已经正确解释了。如果没有,请告诉我。

2 个答案:

答案 0 :(得分:0)

如果您要使用分隔符在单行中打印ID,我建议使用GROUP_CONCAT()。查询如下所示:

SELECT 
    Year(items.sold_date) as 'Year Sold',
    Month(items.sold_date as 'Month Sold',
    GROUP_CONCAT(distinct users.id) as 'Unique User Ids'
FROM users
INNER JOIN items
ON users.id = items.user_id
GROUP BY 
    Year(items.sold_date),
    Month(items.sold_date);

如果您希望每年/每月在多个行上获得期望的结果,则可以通过以下方式将users.id列添加到您的组中:

SELECT * FROM users
INNER JOIN items
ON users.id = items.user_id
GROUP BY 
    Year(items.sold_date),
    Month(items.sold_date),
    users.id;

答案 1 :(得分:0)

看起来像它提供了您想要的输出。

$sql = '
SELECT
    YEAR(I.sold_date) sold_date_Y,
    MONTH(I.sold_date) sold_date_M,
    U.name,
    COUNT(I.user_id)

FROM users 
    AS U

INNER JOIN items 
    AS I 
    ON I.user_id = U.id

GROUP BY 
    YEAR(I.sold_date), 
    MONTH(I.sold_date),
    U.name

ORDER BY
    YEAR(I.sold_date), 
    MONTH(I.sold_date),
    U.name';

$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/>';
    $savYM = $curYM;
}