如何返回10行,其中5是特定值?

时间:2011-10-26 13:07:54

标签: mysql

我有一张特价商品(购物)。该表包含50家商店的特别优惠,其中5家来自奥斯陆,45家来自挪威其他城市。

默认情况下,我想按日期,国家和城市选择10行。

我当前的查询如下所示:

SELECT b.name, a.title, a.shortDescription, a.longDescription, a.startTime, a.endTime, b.fk_countryID, b.city
FROM sl_sale a
LEFT JOIN sl_store b ON a.fk_storeID = b.id
WHERE a.endTime >= NOW()
AND b.fk_countryID = 'NO'
AND b.city = 'Oslo'
ORDER BY a.startTime ASC
LIMIT 10

我的问题是它只会返回5行,因为b.city = 'Oslo'

如何返回10行,其他5行来自a.endTime >= NOW()的其他城市? 我是否必须进行两次查询?

3 个答案:

答案 0 :(得分:2)

如果您首先想要Olso的记录,可以将其从WHERE子句移到ORDER子句:

SELECT b.name, a.title, a.shortDescription, a.longDescription, a.startTime, a.endTime, b.fk_countryID, b.city
FROM sl_sale a
LEFT JOIN sl_store b ON a.fk_storeID = b.id
WHERE a.endTime >= NOW()
AND b.fk_countryID = 'NO'
ORDER BY b.city = 'Oslo' DESC, a.startTime ASC
LIMIT 10

这有效地将其限制为与WHERE条件匹配的10个结果,但b.city = 'Oslo'将被排序到 top 的任何行。 注意:这可能超过5行。

答案 1 :(得分:0)

SELECT b.name, a.title, a.shortDescription, a.longDescription, a.startTime, a.endTime,     b.fk_countryID, b.city
FROM sl_sale a
LEFT JOIN sl_store b ON a.fk_storeID = b.id
WHERE b.fk_countryID = 'NO'
AND (a.endTime >= NOW() OR b.city = 'Oslo')
ORDER BY a.startTime ASC
LIMIT 10

答案 2 :(得分:0)

SELECT b.name, a.title, a.shortDescription, a.longDescription, a.startTime, a.endTime, b.fk_countryID, b.city
FROM sl_sale a
LEFT JOIN sl_store b ON a.fk_storeID = b.id
WHERE (a.endTime >= NOW() OR b.city='Oslo')
AND b.fk_countryID = 'NO'
ORDER BY a.startTime ASC
LIMIT 10