0

我一直试图解决这个问题好几个小时,似乎我被困住了。

当我想要在下面的查询中做的是我将一些位置 ID 传递给IN操作员并且我不希望 MySQL 返回所有结果(表太大)但每个位置 ID 只有 5 个项目(如果项目存在) .

我暂时放了一个LIMIT 100,直到我在你的帮助下完成它。

这是查询:

$sql = "SELECT SQL_CACHE deals.deal_ID, deals.slug, deals.url, deals.previous_price, deals.title, deals.image, deals.price, deals.end, deals.purchases, deals.date_added,
        deals_locations.location_ID, deals.hits
        FROM deals
        INNER JOIN deals_locations
        WHERE deals.status = 'active'
        AND deals_locations.deal_ID = deals.deal_ID
        AND deals_locations.location_ID IN (".implode(', ', $location_IDs).")
        GROUP BY deals.deal_ID
        LIMIT 100;";

非常感谢您的宝贵时间。

编辑:现在我的查询输出如下所示:

SELECT SQL_CACHE deals.deal_ID
    ,deals.slug
    ,deals.url
    ,deals.previous_price
    ,deals.title
    ,deals.image
    ,deals.price
    ,deals.end
    ,deals.purchases
    ,deals.date_added
    ,deals_locations.location_ID
    ,deals.hits
FROM deals
INNER JOIN deals_locations
WHERE deals.status = 'active'
AND (
    SELECT COUNT(*) FROM deals
    WHERE deals.deal_ID = deals_locations.deal_ID
) <= 5
AND deals_locations.deal_ID = deals.deal_ID
AND deals_locations.location_ID IN (1, 2, 3, 5, 7, 12, 13, 26, 27, 28, 29, 30, 31, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 46, 49, 52, 53, 54, 55, 56, 60, 62, 64, 65, 66, 67, 68, 69, 70, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 89, 90, 97, 107, 10, 21, 32, 33, 37, 51, 4, 6, 8, 9, 11, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 45, 47, 48, 50, 57, 58, 59, 61, 63, 71, 73, 84, 85, 86, 87, 88, 91, 92, 93, 94, 95, 96, 98, 99, 100, 101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160)
GROUP BY deals.deal_ID;

但仍显示同一位置的超过 5 条记录。

编辑2:我已经尝试过这种UNION ALL方法并且似乎正在工作。现在我得到了 30 行的总结果,但我担心查询的大小。

这是我的查询现在的样子:http: //pastebin.com/r6vyG594

太大了,explain不能发到网上。我应该怎么做才能使查询高效且尺寸更小?

执行大约需要 0.2158 秒。

4

2 回答 2

0

我可以看到两种方法:

1 子查询而不是 php 内爆:

...
AND deals_locations.location_ID IN (SELECT id FROM deals_locations WHERE .... LIMIT 5)
GROUP BY deals.deal_ID
...

编辑:MySQL 不支持限制子查询

2 在多维数组中创建/使用 5 个元素时限制您的数组

implode(', ', $locations_IDs[0])等等。

你也可以尝试做一个查询/ID

于 2012-09-22T18:08:52.570 回答
-1

首先,我将在您的内部连接中添加一个 ON 语句:

$sql = "SELECT SQL_CACHE deals.deal_ID, deals.slug, deals.url, deals.previous_price, deals.title, deals.image, deals.price, deals.end, deals.purchases, deals.date_added,
    deals_locations.location_ID, deals.hits
    FROM deals
    INNER JOIN deals_locations ON deals_locations.deal_ID = deals.deal_ID AND deals_locations.location_ID IN (".implode(', ', $location_IDs).")

    WHERE deals.status = 'active'
    GROUP BY deals.deal_ID
    LIMIT 100;";

在上面的示例中,我已将与 deal_locations 相关的两个 where 语句移至 join 语句中。这将限制从该表连接多少记录...

于 2012-09-22T18:18:26.487 回答