[英]SQL Multiple columns on one table joined column from other table
I've been trying to run an SQL query but haven't been having much luck. 我一直在尝试运行SQL查询,但是运气不高。 No matter what I do I can't seem to get it to run the way I need it to. 不管我做什么,我似乎都无法使其按我需要的方式运行。 I am able to get the tables to join and get the names across, but I can't get the query output I'm looking for. 我能够使表联接并获得名称,但是我无法获得所需的查询输出。
I have two tables, one table has 3 columns for 1st, 2nd, and 3rd gate techs to be entered. 我有两个表,一个表有3列,分别用于输入第一,第二和第三门技术。 The second table has a list of gate techs we use, the ID for the techs is the primary key. 第二张表列出了我们使用的闸门技术人员列表,技术人员的ID是主键。
What I'm looking for is an SQL statement that will get the the keys from the gate table. 我正在寻找的是一条将从门表中获取密钥的SQL语句。 Example would be Gate Table ID 2 would get 2, 2, 1, then join with the tech table and return the tech names instead of the key. 例如,门表ID 2将得到2、2、1,然后与技术表连接并返回技术名称而不是密钥。
I can one to work if I do the following, but cant get 3 separate columns with the data. 如果执行以下操作,我可以工作,但无法获得3个单独的数据列。
SELECT TName
FROM TechTable
INNER JOIN GateTable
ON GateTabe.Gate1=TechTable.ID
WHERE ID = 3
- -
GateTable
ID Gate1 Gate2 Gate3
1 1 2 3
2 2 2 1
3 4 2 1
- -
TechTable
ID TName
1 Tech1
2 Tech2
3 Tech3
Query Result
ID Gate1 Gate2 Gate3
1 Tech1 Tech2 Tech3
2 Tech2 Tech2 Tech1
3 Tech4 Tech2 Tech1
join
the techTable thrice, once for each different gate. 三次join
techTable,每个不同的门一次。
SELECT g.id,t1.TName as gate1,t2.TName as gate2,t3.TName as gate3
FROM GateTable g
INNER JOIN TechTable t1 ON g.Gate1=t1.ID
INNER JOIN TechTable t2 ON g.Gate2=t2.ID
INNER JOIN TechTable t3 ON g.Gate3=t3.ID
SELECT gt.ID, t1.TName as Gate1, t2.TName as Gate2, t3.TName as Gate3
FROM GateTable gt
LEFT JOIN TechTable t1
ON gt.Gate1=t1.ID
LEFT JOIN TechTable t2
ON gt.Gate2=t2.ID
LEFT JOIN TechTable t3
ON gt.Gate3=t3.ID
You can use INNER JOIN too but it gives you only mapped columns. 您也可以使用INNER JOIN,但是它仅提供映射列。 In your example you specified Gate1 value as 4, but it is not there in TechTable. 在您的示例中,您指定Gate1值为4,但TechTable中没有该值。 In this case, INNER JOIN skips that value. 在这种情况下,INNER JOIN会跳过该值。 But LEFT JOIN would give you mapped values and null for the not available mapping. 但是LEFT JOIN会为您提供映射的值,而对于不可用的映射将为null。 You can use where clause if you need specific GateID. 如果需要特定的GateID,则可以使用where子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.