gpt4 book ai didi

MySQL查询通过列名选择表名

转载 作者:行者123 更新时间:2023-11-29 08:41:30 27 4
gpt4 key购买 nike

我正在尝试从指定数据库中选择包含“lang”和“project”列的所有表。这就是我正在做的事情:

SELECT DISTINCT(ISC1.TABLE_NAME) AS `table` FROM INFORMATION_SCHEMA.COLUMNS AS ISC1 
JOIN INFORMATION_SCHEMA.COLUMNS AS ISC2 ON
(ISC1.TABLE_SCHEMA=ISC2.TABLE_SCHEMA AND ISC1.TABLE_NAME=ISC2.TABLE_NAME AND ISC2.COLUMN_NAME='project')
WHERE ISC1.COLUMN_NAME='lang' AND ISC2.COLUMN_NAME='project' AND ISC1.TABLE_SCHEMA='some_database'
  • 它确实有效,但我有一种感觉,这是编写此类查询的糟糕方法。如果有人可以改进它,那就太好了。
  • 现在我必须更改此查询以选择具有“lang”列但没有“project”列的所有表。老实说,我不知道从哪里开始......

感谢您的帮助

最佳答案

SELECT DISTINCT(ISC1.TABLE_NAME) AS `table`
FROM INFORMATION_SCHEMA.COLUMNS AS ISC1,
INFORMATION_SCHEMA.COLUMNS AS ISC2
WHERE ISC1.TABLE_SCHEMA=ISC2.TABLE_SCHEMA
AND ISC1.TABLE_NAME=ISC2.TABLE_NAME
AND ISC2.COLUMN_NAME='project'
AND ISC1.COLUMN_NAME='lang'
AND ISC1.TABLE_SCHEMA='some_database'

没有项目栏:

SELECT DISTINCT(ISC.TABLE_NAME) AS `table`
FROM INFORMATION_SCHEMA.COLUMNS AS ISC
WHERE ISC.COLUMN_NAME='lang'
AND ISC.TABLE_SCHEMA='some_database'
AND NOT EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = 'project'
AND C.TABLE_NAME=ISC.TABLE_NAME
AND C.TABLE_SCHEMA=ISC.TABLE_SCHEMA)

关于MySQL查询通过列名选择表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com