我有按价格订购的产品。 如何选择价格低于1欧元的所有产品,否则继续搜索至少选择X产品。
SQL查询每次都必须返回至少X行。
答案 0 :(得分:-1)
以下是Microsoft SQL Server中的内容。我并不熟悉Mysql,但我想象的逻辑保持不变。而不是" TOP"你必须在底层查询中使用LIMIT。
DECLARE @Price as Money
SET @Price = 1
IF (SELECT COUNT(1) FROM Product WHERE Price < @Price) > 50
SELECT
ProductName
FROM
Product
WHERE Price < @Price
ELSE
SELECT TOP 50
ProductName
FROM Product
ORDER BY Price
粗略的MySQL转换:
DECLARE PriceVar as DECIMAL(13,2)
SET PriceVar = 1
IF (SELECT COUNT(1) FROM Product WHERE Price < PriceVar) > 50
SELECT
ProductName
FROM
Product
WHERE Price < PriceVar
ELSE
SELECT
ProductName
FROM Product
ORDER BY Price LIMIT 50
答案 1 :(得分:-1)
这是单一选择解决方案,希望它对您有所帮助。
SELECT * FROM (
(
SELECT
productname
FROM
Product
WHERE Price < :Price
)
union all
(
SELECT
productname
FROM
Product
order by price desc limit :X
)
) x limit :X
根据执行次数和表的大小,可以执行inpact,但可以通过将顶级产品,第二个内部查询缓存到不同的表中来解决。