Sql从同一个表中获取特定的列

时间:2017-02-01 12:11:30

标签: mysql sql

这是我的表

-----------------------------------------------------------
id | tempname | col1 | col2 | col3 | col4 | col5 | col6
-----------------------------------------------------------
1  |    1     |   on |  off |  off  |  on  |  off |    off
-----------------------------------------------------------
2  |     2    |  off |   off|  on   | off  |  off |   on
-----------------------------------------------------------
  

我想从上面的表中获取其值为on的数据,我不想要另一列我只想要那些有价值的列

结果: 这是我的表

-----------------------------------------------------------
id | tempname | col1 | col3 | col4 | col6
-----------------------------------------------------------
1  |    1     |   on |  off |  on  | off
-----------------------------------------------------------
2  |     2    |  off | on  |  off  | on
-----------------------------------------------------------

我不想要任何额外的列 我想使用select *查询。 我不想在选择查询

中指定列名

1 个答案:

答案 0 :(得分:0)

您可能需要依次查看每个列(使用information_schema列)并检查是否有任何行具有'on'值,然后跟踪它们,然后从您创建的列创建自定义sql语句发现它确实至少有一行具有该值。

以下代码适用于sql server,您需要调整它以便与mySql一起使用。

然后,您可以从中创建存储过程,然后执行该

NB。对于非常大的表,代码可能会很慢,即使检查每列是否有任何“ons”的部分只检查找到的第一个匹配项(使用TOP 1)

DECLARE @sqlCountOn NVARCHAR (MAX)
DECLARE @ParmDefinition NVARCHAR (MAX)
DECLARE @colName nvarchar(50)
DECLARE @countOn int
DECLARE @colsToInclude NVARCHAR (MAX)
DECLARE @query NVARCHAR(MAX)
DECLARE @tableName NVARCHAR(50)
DECLARE @columnWildcard NVARCHAR(50)

-- define the columns you always want in the query results
SET @colsToInclude = 'id,tempname'
set @tableName='test'
set @columnWildcard = 'col%'

-- get a list of columns to check for on/off using a wildcard on the name
DECLARE columnCursor cursor for SELECT COLUMN_NAME 
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = @tableName and COLUMN_NAME like @columnWildcard order by ordinal_position
OPEN columnCursor   

FETCH NEXT FROM columnCursor INTO @colName
--loop through all the columns that we want to look for on/off
WHILE @@FETCH_STATUS = 0   
BEGIN   

       --build a query to count if we have *any* 'on's we have for this column
       SET @sqlCountOn = 'select @retValOut= COUNT(*) from (select top 1 ' + @colName + ' from ' + @tableName + ' where ' + @colName + '=''on'')'
       SET @ParmDefinition = N'@retvalOUT int OUTPUT';

       EXEC sp_executesql @sqlCountOn, @ParmDefinition, @retvalOUT=@countOn OUTPUT;
       --check the count and if it's greater than 0 we want to include it, so add the column name to the output column list
       if @countOn >0 set @colsToInclude=@colsToInclude + ',' + @colName 

       FETCH NEXT FROM columnCursor INTO @colName   
END

CLOSE columnCursor   
DEALLOCATE columnCursor

--now create the query that will output just the columns we want from the table
set @query='select ' + @colsToInclude + ' from [' + @tableName + '] '

EXEC SP_EXECUTESQL @query