简体   繁体   中英

SELECT columns based on a subquery results with single statement

I have two tables in the database: Artist and Filter . Is there anyway to query columns of Artist based on the subquery results of Filter in a single SQL statement?

Pseudo Code:

SELECT (SELECT ColumnName FROM Filter WHERE ShowColumn=1) FROM Artist

  • Artist
------------------------------------------
| id | FirstName | LastName | Genre      |
------------------------------------------
| 1  | John      | Coltrane | Jazz       |
| 2  | Jimi      | Hendrix  | Rock       | 
| 3  | Ulrich    | Schnauss | Electronic |
------------------------------------------
  • Filter
--------------------------------
| id | ColumnName | ShowColumn |
--------------------------------
| 1  | FirstName  | 1          |
| 2  | LastName   | 0          |
| 3  | Genre      | 1          |
--------------------------------
  • Expected Results
-------------------------------
| id | FirstName | Genre      |
-------------------------------
| 1  | John      | Jazz       |
| 2  | Jimi      | Rock       | 
| 3  | Ulrich    | Electronic |
-------------------------------

The best I can have is to use multiple CASE..WHEN , but it isn't so elegant and there're some extra annoying NULL fields.

SELECT 
    CASE WHEN (SELECT ShowColumn FROM Filter WHERE ColumnName='FirstName') THEN FirstName END, 
    CASE WHEN (SELECT ShowColumn FROM Filter WHERE ColumnName='LastName')  THEN LastName  END, 
    CASE WHEN (SELECT ShowColumn FROM Filter WHERE ColumnName='Genre')     THEN Genre     END
FROM Artist

This is not possible in SQLite.

You have to read the columns from Filter first, and then to construct a query with those columns.

If your target is formatted output, ie, you don't need a dataset, you can compose a string in first column.

Example for CSV output:

SELECT --Header
    'id'
    ||CASE (SELECT ShowColumn FROM Filter WHERE ColumnName='FirstName') WHEN 1 THEN ',FirstName' ELSE '' END
    ||CASE (SELECT ShowColumn FROM Filter WHERE ColumnName='LastName') WHEN 1 THEN ',LastName' ELSE '' END
    ||CASE (SELECT ShowColumn FROM Filter WHERE ColumnName='Genre') WHEN 1 THEN ',Genre' ELSE '' END
UNION ALL
SELECT --Data
    CAST(id AS TEXT)
    ||CASE WHEN mf=1 THEN ','||CAST(FirstName AS TEXT) ELSE '' END
    ||CASE WHEN ml=1 THEN ','||CAST(LastName AS TEXT) ELSE '' END
    ||CASE WHEN mg=1 THEN ','||CAST(Genre AS TEXT) ELSE '' END
FROM Artist
JOIN (SELECT ShowColumn AS mf FROM Filter WHERE ColumnName='FirstName')
JOIN (SELECT ShowColumn AS ml FROM Filter WHERE ColumnName='LastName')
JOIN (SELECT ShowColumn AS mg FROM Filter WHERE ColumnName='Genre')
;

what about this query:

select distinct a.id, a.FirstName, a.Genre 
from Artist a, Filter f 
where f.ShowColumn = 1

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