简体   繁体   English

在“商品”条件和[此列中至少有一个值]中显示列

[英]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 我只需要获取与诸如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]

Is it even possible? 可能吗

You can put condition on the rows that you want to fetch, the where clause is responsible for it. 您可以在要获取的行上放置条件,where子句对此负责。 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. 所需的列仅在select语句中指定,无法指定要选择的列。 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. 我猜你想要的是具有category_id = 5的非空值的列名。这里的困难是找出哪些类别具有category_id = 5的非空值。这必须在一个每列,但可以做到。

To be honest... I don't work in MySql but I'm certain you can follow along and make any adjustments needed. 说实话...我不在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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