从货物显示列WHERE条件AND [列中至少有一个值]

时间:2012-03-31 15:41:40

标签: mysql sql

我有一个包含许多不同列的表,例如

resolution, brightness, type, width, camera_type, projection_type etc 

我需要获取那些与LED电视相关的列的名称来构建过滤器,这意味着我需要以某种方式

SHOW COLUMNS FROM Goods WHERE category_id = 5 AND [there is at least one value in the column for a row that meets the category_id = 5 condition]

甚至可能吗?

2 个答案:

答案 0 :(得分:0)

您可以将条件放在要获取的行上,where子句负责它。您想要的列只在select语句中指定,无法指定要选择的列。获得结果后,您可以根据值确定要使用的列。

答案 1 :(得分:0)

我猜你想要的是具有非null值的列名,其中category_id = 5.这里的难点是找出哪些列具有非null值,其中category_id = 5.这将具有可以按列完成,但可以完成。

说实话......我不能在MySql中工作,但我确定你可以跟进并做出任何调整。

-- create a temp table to hold the results
CREATE TEMPORARY TABLE TempTable (columnName varchar(100));  

-- create a bunch of dynamic SQL to insert its name into the temp table when category_id = 5 and its value is not null

DECLARE column_name VARCHAR(100);

DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;

-- Declare the cursor
DECLARE columns_cur CURSOR FOR
  SELECT
      column_name
  FROM information_schema.columns
  WHERE TABLE_NAME = 'Goods';

-- Declare 'handlers' for exceptions
DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET no_more_rows = TRUE;

OPEN columns_cur;
  select FOUND_ROWS() into num_rows;

the_loop: LOOP

  FETCH  columns_cur 
  INTO   column_name;

  IF no_more_rows THEN
      CLOSE columns_cur;
      LEAVE the_loop;
  END IF;

  PREPARE stmt FROM 'IF(EXISTS(SELECT * FROM Goods WHERE ? IS NOT NULL AND catetory_id = 5)) INSERT INTO TempTable (column_name) VALUES ('?');'

  EXECUTE stmt USING @column_name;
  DEALLOCATE PREPARE stmt;

END LOOP the_loop;