MySql选择两个变量

时间:2012-07-18 14:43:11

标签: mysql select

我有一个从1到1000的id表。如何从表中选择行并将结果插入到我声明的两个变量中?

有些事情是这样的:

Select from table1 where id = 1 or id = 27 into var1, var2

2 个答案:

答案 0 :(得分:1)

您可以这样做,但您需要确认以下两个限制:

  1. 结果集必须只包含一行
  2. 该行必须包含两列
  3. 见:

    SELECT 'foo', 4 FROM DUAL INTO @a, @b;
    
    SELECT @a, @b;
    +------+------+
    | @a   | @b   |
    +------+------+
    | foo  |    4 |
    +------+------+
    

    也有可能:

    SELECT MIN(id), MAX(Population) FROM world.City INTO @min_id, @max_pop;
    
    SELECT name, population FROM world.Country LIMIT 1 INTO @name, @pop;
    

答案 1 :(得分:1)

SELECT
    @var1 := MAX(IF(id = 1, some_field, NULL)),
    @var2 := MAX(IF(id = 27, some_field, NULL))
FROM table
WHERE id IN (1,27);