[英]referencing name of table from another table in sql query
我有3张桌子。
1个主表-具有列的组件-ID,name_of_component,ID_component
和2个表格的组件
首先-具有列的Hardisk-ID,容量
秒-带列的RAM-ID,速度
在主表中,我有组件的ID,详细信息在表hardisk或RAM中。 列name_of_component选择硬键或RAM,而ID_component从该表中选择正确的详细信息。
例如,可以说在主表中是此行
并且在RAM表中有两行
我尝试过这样的事情
Select *
from (Select name_of_component
from Component
where ID=1)
join Component on (Select name_of_component
from Component
where ID=1).ID = Component.ID_component
但这是行不通的。 那么有什么办法,如何从表中调用从另一个表中选择名称的信息呢? 我无法使用一张表来显示RAM和图形卡的详细信息,因为它们具有不同的详细信息。 那么我该怎么做呢?
语法错误是您输入的SQL语句包含无效的FROM子句。
您无法在SQL本身中执行此操作。 我想你可以做一个工会:
select * from ram join component on ram.id=component.id where component.name_of_component='RAM' and component.id=myid
union
select * from harddisk join component on ram.id=component.id where component.name_of_component='harddisk' and component.id=myid
由于name_of_component只能同时是这些值之一,因此并集的一部分将不返回任何内容,而另一部分将返回正确的部分。 但这仅在两个表的列数相同时才有效。 如果两个表的布局相似,则可能不需要两个表。
由于多种原因,您无法使用简单的SQL来完成所需的操作。 最明显的是,SQL查询返回一组固定的列,并且在编写代码时定义了这些列。
解决此限制的方法是使用准备好的语句,例如:
select @t = name_of_component
from MainTable
where id = 1;
select @sql = replace(replace('select * from @table where id = @i',
'@i', 1
), '@table', @t);
prepare stmt from @sql;
execute stmt;
另一种方法是使用left join
:
select mt.id, r.ram, hd.speed
from MainTable mt left join
RAM r
on mt.id = r.id left join
HardDisk hd
on mt.id = hd.id;
所需的值将在相应的列中。 您可以将其放在视图中。
您可能会发现,EAV(实体-属性-值)结构可以更好地表示此数据。 您的主表将具有组件,ID和类型。 第二张表将列出所有组件的功能,并带有以下行:
id attribute value
1 'RAM' '2GB'
2 'RAM' '4GB'
3 'Speed' '7kRPM'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.