简体   繁体   中英

SHOW COLUMNS FROM Goods WHERE condition AND [there is at least one value in the column]

I have a table with lots of different columns, like

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

I need to get the names of only those columns, that are relevant to, say LED tv's to build filters, - which means I need to somehow

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]

Is it even possible?

You can put condition on the rows that you want to fetch, the where clause is responsible for it. The columns that you want are to be specified in the select statement only, there is no way to specify which column to be selected. Once you have the results you can decide which columns to use, depending upon the value.

I'm guessing what you want is the column names that have a non-null value where category_id = 5. The difficulty here is finding out which columns have a non-null value where category_id = 5. This will have to be accomplished on a per column basis but can be done.

To be honest... I don't work in MySql but I'm certain you can follow along and make any adjustments needed.

-- 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM