2015-03-31 99 views
0

如果我有一個如下定義的表格:mytable(model char(4), price int);並且我試圖找到與給定基準價格的價格最接近的價值,那麼我該如何去做呢?SELECT INTO with LIMIT

什麼我是這樣的:

delimiter // 
CREATE FUNCTION findClosestPrice (value int) returns int 
BEGIN 
    DECLARE closestPrice int default -1; 
    DECLARE row int default 0; 
    DECLARE rows int default 0; 
    DECLARE currPrice int default -1; 
    select count(*) from mytable into rows; 
    SET row=0; 
    WHILE row < rows DO 
     select price from mytable limit row, 1 into currPrice; <----- this gives an error 
     SET row = row + 1; 
    END WHILE; 
END// 

爲什麼我不能有一個線?
如何從循環中的當前行中選擇價格並將其保存到我聲明的變量中?我認爲這會起作用,但事實並非如此。

回答

1

你可以找到最接近的價格爲基準價格與單查詢:

SELECT model,price,(ABS(price-basePrice)) AS price_diff FROM mytable ORDER BY price_diff LIMIT 1 
0

into必須跟在from之前的列名稱。

更改

select price from mytable limit row, 1 into currPrice; 

select price into currPrice from mytable limit row, 1; 

參考

SELECT Syntax
... INTO子句可以出現兩種如圖 語法描述或立即select_expr列表 以下...

+0

改變,仍然留給我一個錯誤 – ZWiki 2015-03-31 16:05:12

+0

這是什麼*錯誤*閱讀!!? – 2015-03-31 16:08:05

+0

'錯誤1064(42000):您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊,在'row,1'附近使用正確的語法;' – ZWiki 2015-03-31 16:09:30