SQLITE: 作为子查询选择的表名

huangapple go评论59阅读模式
英文:

SQLITE: Table names to select from as a subquery

问题

我正在尝试从多个表中一次性选择一个列的不同值。 我要合并的两个查询如下:

1. 选择所有适当的表:
```sql
SELECT name
FROM sqlite_schema 
WHERE type='table' 
	AND name NOT LIKE 'sqlite_%';
  1. 从一个表中选择不同的值:
SELECT DISTINCT CATEGORY FROM my_table;

我想在第一个查询的结果中对每个表名运行最后一个查询。 我相当肯定这是可能的,但还没有搞清楚。

我想象的是类似这样的东西:

SELECT DISTINCT CATEGORY 
FROM (
	SELECT name
	FROM sqlite_schema 
	WHERE type='table' 
		AND name NOT LIKE 'sqlite_%'
);

这个合并的查询会引发错误。


<details>
<summary>英文:</summary>

I&#39;m trying to select distinct values of one column from many tables at once. The two queries I want to combine are:

1. Select all the appropriate tables:
```sql
SELECT name
FROM sqlite_schema 
WHERE type=&#39;table&#39; 
	AND name NOT LIKE &#39;sqlite_%&#39;;
  1. Select distinct values from one table:
SELECT DISTINCT CATEGORY FROM my_table;

I want to run this last query on each table name from the results of the first query. I'm pretty sure it should be possible, but haven't worked it out.

Something like this is what I imagine:

SELECT DISTINCT CATEGORY 
FROM (
	SELECT name
	FROM sqlite_schema 
	WHERE type=&#39;table&#39; 
		AND name NOT LIKE &#39;sqlite_%&#39;
);

This combined query throws an error.

答案1

得分: 1

以下是翻译好的部分:

SQLite 最好的用法是将所需的 SQL 语句作为字符串获取,然后使用您选择的编程语言执行它:

SELECT GROUP_CONCAT('SELECT CATEGORY FROM ' || name, ' UNION ') AS sql
FROM sqlite_schema 
WHERE type='table' AND name NOT LIKE 'sqlite_%';

您将获得一个字符串,类似于:

SELECT CATEGORY FROM table1 
UNION 
SELECT CATEGORY FROM table2 
UNION 
SELECT CATEGORY FROM table3

我使用 UNION 而不是 SELECT DISTINCT

请查看演示

英文:

The best that you can do with SQLite is get the sql statement that you need as a string and execute it with the programming language of your choice:

SELECT GROUP_CONCAT(&#39;SELECT CATEGORY FROM &#39; || name, &#39; UNION &#39;) AS sql
FROM sqlite_schema 
WHERE type=&#39;table&#39; AND name NOT LIKE &#39;sqlite_%&#39;;

You will get a string like:

SELECT CATEGORY FROM table1 
UNION 
SELECT CATEGORY FROM table2 
UNION 
SELECT CATEGORY FROM table3

I use UNION instead of SELECT DISTINCT.<br/>

See the demo.<br/>

huangapple
  • 本文由 发表于 2023年2月10日 02:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75402972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定