简体   繁体   English

我尝试加入两个表,但另一个表名在第一个表的列中。 是否可以加入或是否有

[英]I try to join two table but another table name is in column of first table. Is it possible to join or is there is an

Joining two tables...one table name is also the column name.加入两个表...一个表名也是列名。 SQL SQL

FROM table fs
INNER JOIN fs.tablenamecolumn st 
ON fs.t_ID=st.t_ID
where t=1250```

error--
Invalid object name 'fs.tablenamecolumn '.

Edit: I just realised this is for MySQL, Not MSSQL.编辑:我刚刚意识到这是针对 MySQL,而不是 MSSQL。 SO you will need to use a prepare statement.所以你需要使用准备语句。 hopefully you can use the below as a guide to help you.希望您可以使用以下内容作为指南来帮助您。

You will need to create the SQL dynamically eg您将需要动态创建 SQL,例如

DECLARE @tablename AS VARCHAR(100)
SELECT  @tablename = tablnamecolumn FROM [yourtable]

DECLARE @query AS NVARCHAR(MAX)
SET     @query = 
'SELECT * 
 FROM [yourtable] 
 INNER JOIN ' + @tablename + ' 
 ON fs.t_ID=st.t_ID
 WHERE t=1250'

EXEC sp_executesql @query

On where condition give table alias name on column the alias name will be on which table you want filtering.在 where 条件下,在列上给出表别名,别名将在您要过滤的表上。

select FROM table fs
INNER JOIN fs.tablenamecolumn st 
ON fs.t_ID=st.t_ID
where fs.t=1250

Not really.并不真地。 This is even quite hard using dynamic SQL because the name might change from row to row.使用动态 SQL 甚至很难做到这一点,因为名称可能会逐行更改。

You should revisit your data model.您应该重新审视您的数据模型。 What you are doing is probably quite unnecessary.你正在做的事情可能是不必要的。

If there is a finite set of tables, you can use left join :如果有一组有限的表,您可以使用left join

FROM table fs LEFT JOIN
     table1 t1
     ON fs.t_ID = t1.t_ID AND
        fs.tablenamecolumn = 'table1' LEFT JOIN
     table2 t2
     ON fs.t_ID = t2.t_ID AND
        fs.tablenamecolumn = 'table2' LEFT JOIN
     . . .
WHERE fs.t = 1250

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

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