简体   繁体   English

查找外键引用字段的值

[英]Finding the values of the foreign key referenced field

I have here an SQL query that I got from this source . 我这里有一个从此来源获得的SQL查询。 What it does is it finds all the primary keys and their references in the database. 它的作用是在数据库中找到所有主键及其引用。

select
    concat(table_name, '.', column_name) as 'foreign key',  
    concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database'

I modified it a little to become this 我做了一点修改就变成了这个

select
    table_name as fk_table_name, column_name as 'foreign key',  
    referenced_table_name as ref_table_name, referenced_column_name as 'references'
from
    information_schema.key_column_usage
inner join
    information_schema.referenced_table_name
where
    referenced_table_name is not null
    and column_name = 'customer_number'
    and referenced_table_name = 'accepted_orders'

Now it doesn't work. 现在,它不起作用。 The error it returns is ' #1109 - Unknown table 'referenced_table_name' in information_schema'. 它返回的错误是'#1109-information_schema中的未知表'referenced_table_name'。 My goal is instead of just displaying what the referenced column name is, it gives me all the values of that column instead. 我的目标不仅是显示引用的列名称是什么,它还为我提供了该列的所有值。

So instead of telling me that the foreign key customer_number in accepted_orders references the primary key customer_number in customer_records, I want to get all the values of customer_number in customer_records instead. 因此,我不是要告诉我accepted_orders中的外键customer_number引用了customer_records中的主键customer_number,而是要获取customer_records中的customer_number的所有值。

I thought of using an inner join on the result of the query but apparently it won't let me. 我考虑过在查询结果上使用内部联接,但显然它不允许我这样做。 How do I do this? 我该怎么做呢? Do I have to use separate SQL statements? 我是否必须使用单独的SQL语句?

You seem to be, as the error message says, using referenced_table_name in a context where the query parser wants a table name, not a column name. 如错误消息所述,您似乎在查询解析器需要表名而不是列名的上下文中使用referenced_table_name You wrote: 你写了:

inner join
   information_schema.referenced_table_name

That doesn't make any sense because you're trying to join to a column, not a table. 这没有任何意义,因为您试图连接到列而不是表。

Try omitting the two lines above from your query. 尝试从查询中省略上面的两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM