2015-10-15 52 views
4

下按預期工作:mysql的變量具有多個值時,有存儲在一個變量的單個值

Set @var = 121; 
select * from table where id = @var; 

如何設置有多個變量的值,然後在查詢中使用它。我曾經試過,但它不工作:

set @var = (
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191, 
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191, 
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191 
) 
select * from table where id = @var; 

回答

0

則應使用

select * from table where id IN (@var); 
+1

這會引發一個「錯誤1241(21000):操作數應該包含1列」。 –

3
set @var = ' 
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191, 
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191, 
    117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191' 

SELECT * FROM table WHERE FIND_IN_SET(id,@var); 

謝謝哥們

1

您就可以向該通過設置@var爲逗號分隔字符串並使用喜歡獲取數據。這並不完美但可行,您必須注意@var中的值。不應該有任何無效字符像space

Mysql> set @var = '117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,117,120,121,122,143,151,175,233,12'; 
Query OK, 0 rows affected (0.00 sec) 

Hitesh> select * from test where ((@var like concat(id,',%')) or (@var like concat('%,',id)) or (@var like concat('%,',id,',%')) or (@var like id)); 
+----+------+-------+ 
| ID | NAME | VALUE | 
+----+------+-------+ 
| 12 | Nee | NULL | 
+----+------+-------+ 
1 row in set (0.00 sec) 

您還可以使用LOCATE函數代替like。 MySQL LOCATE()返回字符串中第一次出現字符串的位置。這兩個字符串都作爲參數傳遞。可以使用可選參數來指定字符串的哪個位置(即要搜索的字符串)將開始搜索。如果未提及此位置,則搜索從頭開始。

語法LOCATE(substr,str)

mysql> SELECT LOCATE('st','myteststring'); 
+-----------------------------+ 
| LOCATE('st','myteststring') | 
+-----------------------------+ 
|       5 | 
+-----------------------------+ 

FIND_IN_SET()是您完美的情況下一個。它的must have strin g值爲comma separated