我想获取两列特定列之间的列值

时间:2015-12-18 07:43:56

标签: mysql sql select case between

我有一个表,我必须在其中选择两列之间的列值。假设column1column2column3位于column_start中的column_endtable1之间。 column_startcolumn_end之间的列会根据需要添加。

表1

column_start | column1 | column2 | column3 | column_end
-------------------------------------------------------
     1       |    2    |    3    |    4    |     5
     8       |    5    |    6    |    4    |     2

是否可以获得这些column1column2column3值?

输出:

 column1 | column2 | column3
----------------------------  
   2     |    3    |    4     
   5     |    6    |    4      

3 个答案:

答案 0 :(得分:3)

如果我理解正确,我认为你不能用一个查询来做到这一点。您可以尝试使用以下内容。添加了对代码的评论。

SET @schema = 'database_name_here'; -- Database name
SET @table = 'table1';              -- Table name
SET @startColumn = 'column_start';
SET @endColumn = 'column_end';

-- First get the position of both columns
SELECT ORDINAL_POSITION FROM information_schema.COLUMNS 
    WHERE table_schema=@schema AND table_name=@table AND 
    column_name=@startColumn INTO @StartPosition;

SELECT ORDINAL_POSITION FROM information_schema.COLUMNS 
    WHERE table_schema=@schema AND table_name=@table AND 
    column_name=@endColumn INTO @endPosition;

-- get the column names from the position
SELECT GROUP_CONCAT(column_name) from information_schema.COLUMNS
    where table_schema=@schema AND table_name=@table
    AND ORDINAL_POSITION > @StartPosition AND ORDINAL_POSITION < @endPosition 
    INTO @colname;

-- create a sql statement prepare and execute
SET @query = CONCAT('SELECT ',@colname,' FROM ', @table);
PREPARE stmt FROM @query;
EXECUTE stmt;

答案 1 :(得分:2)

SELECT column1, column2, column3
FROM yourTable
WHERE
    column1 > column_start AND column1 < column_end AND
    column2 > column_start AND column2 < column_end AND
    column3 > column_start AND column3 < column_end

答案 2 :(得分:2)

试试这个:

SELECT CASE WHEN column_start < column_end AND column1 BETWEEN column_start AND column_end THEN column1 
            WHEN column_end < column_start AND column1 BETWEEN column_end AND column_start THEN column1 
            ELSE NULL 
       END AS column1, 
       CASE WHEN column_start < column_end AND column2 BETWEEN column_start AND column_end THEN column2
            WHEN column_end < column_start AND column2 BETWEEN column_end AND column_start THEN column2 
            ELSE NULL 
       END AS column2,
       CASE WHEN column_start < column_end AND column3 BETWEEN column_start AND column_end THEN column3
            WHEN column_end < column_start AND column3 BETWEEN column_end AND column_start THEN column3 
            ELSE NULL 
       END AS column3
FROM table1;