Skip to content
Advertisement

SQL SELECT from based on truth table

How can I select the columns to be returned by a lookup truth table? my data:

| nam | X | Y |
| Bob | 2 | 5 |
| Jan | 1 | 6 |

the lookup table

| prop| SHOW |
| nam | true |
|  X  | false|
|  Y  | true |

someting like SELECT from data (columns which have "true" in lookup) resulting in:

| nam | Y |
| Bob | 5 |
| Jan | 6 |

Advertisement

Answer

use a pivot table

Schema (MySQL v5.7)

CREATE TABLE tab1 (
  `nam` VARCHAR(3),
  `X` INTEGER,
  `Y` INTEGER
);

INSERT INTO tab1
  (`nam`, `X`, `Y`)
VALUES
  ('Bob', '2', '5'),
  ('Jan', '1', '6');

CREATE TABLE tab2 (
  `prop` VARCHAR(3),
  `SHOW` VARCHAR(5)
);

INSERT INTO tab2
  (`prop`, `SHOW`)
VALUES
  ('nam', 'true'),
  ('X', 'false'),
  ('Y', 'true');

Query #1

SELECT CONCAT ('SELECT ',GROUP_CONCAT(CONCAT('`',prop,'`')),' FROM tab1;') 
       INTO @sql 
FROM tab2 WHERE `SHOW` = 'true';

There are no results to be displayed.


Query #2

PREPARE stmt FROM @sql;

There are no results to be displayed.


Query #3

EXECUTE stmt;

| nam | Y   |
| --- | --- |
| Bob | 5   |
| Jan | 6   |

There are no results to be displayed.


View on DB Fiddle

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement