[英]How to filter columns of one table by values given as rows in another table?
I have two tables in MySQL.我在 MySQL 中有两张桌子。 I would like to select columns from main_table which are given as rows in cols_filter table (it is a small table which can be edited at any time).
我想 select 列来自main_table ,它们在cols_filter表中作为行给出(这是一个可以随时编辑的小表)。
main_table:主表:
+--------+--------+---------+-------+-------+
| Col_A | Col_B | Col_C | Col_D | Col_E |
+--------+--------+---------+-------+-------+
| Apple | 585416 | Monday | 0 | Y |
| Banana | 857463 | Sunday | 1 | N |
| Orange | 852147 | Friday | 0 | N |
| Plum | 753951 | Sunday | 1 | Y |
| Peach | 448691 | Monday | 0 | N |
+--------+--------+---------+-------+-------+
cols_filter: cols_filter:
+--------+
| names |
+--------+
| Col_A |
| Col_B |
| Col_E |
+--------+
Expected output:预期 output:
+--------+--------+-------+
| Col_A | Col_B | Col_E |
+--------+--------+-------+
| Apple | 585416 | Y |
| Banana | 857463 | N |
| Orange | 852147 | N |
| Plum | 753951 | Y |
| Peach | 448691 | N |
+--------+--------+-------+
I was trying to create a subquery with GROUP_CONCAT to have all rows from cols_filter as comma seperated values in one line:我试图使用 GROUP_CONCAT 创建一个子查询,以将cols_filter中的所有行作为逗号分隔值放在一行中:
SELECT GROUP_CONCAT(names) AS Columns
FROM cols_filter
+---------------------+
| Columns |
+---------------------+
| Col_A, Col_B, Col_E |
+---------------------+
... and using it as a list in main query instead of putting certain column names there, but it did not work. ...并将其用作主查询中的列表,而不是将某些列名放在那里,但它不起作用。
I was not able to find a similar question here.我在这里找不到类似的问题。 Any ideas?
有任何想法吗?
Framing SQL cannot be dynamic within database itself, but can be achieved through little programming on top.框架 SQL 在数据库本身内不能是动态的,但可以通过顶部的少量编程来实现。 You can use any programming language(python/java/scala) to generate the SQL dynamically and fire the query to the database.
您可以使用任何编程语言(python/java/scala)动态生成 SQL 并将查询发送到数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.