0

现在,在我问这个之前......让我说我已经像以往一样搜索并尝试了一些似乎不起作用的东西,我不知道我做错了什么。

我有一个网站,用户(具有不同的“owner_id”)可以列出一个或多个产品。在一个特殊页面上,我想每个“owner_id”只显示一个产品,这应该是最新的。

我尝试了 DISTINCT 查询,但由于某种原因它仍然返回所有产品。我究竟做错了什么?这里是:

$sql_select_recent_items = $db->query("SELECT DISTINCT owner_id, start_time, name, price, owner_id 
    FROM db_products 
    FORCE INDEX (products_start_time)
    WHERE closed=0 AND active=1 AND approved=1 AND deleted=0 AND creation_in_progress=0 
    ORDER BY start_time DESC;

我也试过:

$sql_select_recent_items = $db->query("SELECT DISTINCT(owner_id), start_time, name, price, owner_id 
    FROM db_products 
    FORCE INDEX (products_start_time)
    WHERE closed=0 AND active=1 AND approved=1 AND deleted=0 AND creation_in_progress=0 
    ORDER BY start_time DESC;

以上两种方法似乎都不起作用。我究竟做错了什么?我只想显示最近的项目(ORDER BY start_time DESC),并且每个“owner_id”仅限于 1 个项目。

4

3 回答 3

0

也许

SELECT owner_id, MIN(start_time), name, price
FROM db_products 
WHERE closed=0 AND active=1 AND approved=1 AND deleted=0 AND creation_in_progress=0 
GROUP BY owner_id

ORDER BY start_time DESC如果您希望最终列表(owner_id、start_id、name、price)按 start_id 排序,您可以添加。

于 2013-09-27T14:29:48.267 回答
0

尝试:

SELECT DISTINCT(owner_id), start_time, name, price
FROM db_products 
WHERE closed=0 AND active=1 AND approved=1 AND deleted=0 AND creation_in_progress=0 
group by owner_id
ORDER BY start_time DESC;
于 2013-09-27T13:03:24.243 回答
0

我发现了这个问题。我需要在 GROUP BY 之前执行 ORDER BY,这通常是不可能的。可以在这里找到问题的解决方案:

http://arfeen.net/2012/10/mysql-use-of-group-after-order-by/

于 2013-09-28T00:13:23.040 回答