I have a stored procedure that needs to pull info from the same table twice. How do I use Correlation Names?

淺唱寂寞╮ 提交于 2020-01-04 06:40:01

问题


I am creating a game cheat page for the game Doodle Creatures. The table I have created takes the ID's of the Combo Animal, the Gene it is combined with, and that of the New animal from the Animals table to display the information. The table looks like this:

Creature Combos Table:
ComboID (PK) | NewAnimalID (FK) | ComboAnimalID (FK) | GeneID (FK) |

The procedure I created to select records from the Combos table populates my datalist with information about the combo animal, gene, and new animal by joining the Animal and Genes tables based on the ID's of the combo, new animal, and genes.:

CREATE PROCEDURE [dbo].[SelectCreatureCombos]
AS
    SELECT * FROM [CreatureCombos]
    INNER JOIN [Animals] ON [CreatureCombos].[NewCreatureID] = [Animals].[AnimalId]
    INNER JOIN [Animals] ON [CreatureCombos].[ComboAnimalID] = [Animals].[AnimalId]
    INNER JOIN [Genes] ON [CreatureCombos].[ComboGeneID] = [Genes].[GeneId] ;

Desired Results of Procedure:

(New) Animal (Name) | AnimalImg | AnimalAltText | AnimalToolTip | (Combo) Animal (name) | AnimalImg | AnimalAltText | AnimalToolTip | Gene | GeneImg | GeneAltText | GeneToolTip | 

When I run the page, I get the following error:

The objects "Animals" and "Animals" in the FROM clause have the same exposed names. Use correlation names to distinguish them.

I must admit I am still a little new to SQL; I can insert, select, and update like a pro, but joins and aliases and correlation names are a little beyond me. Any other advice would be greatly appreciated. Thanks!


回答1:


If that's the case, all you need to do is to supply an ALIAS on the table name to avoid name collision. eg

SELECT * 
FROM [CreatureCombos]
     INNER JOIN [Animals] AS Animal1 
           ON [CreatureCombos].[NewCreatureID] = Animal1.[AnimalId]
     INNER JOIN [Animals] AS Animal2 
           ON [CreatureCombos].[ComboAnimalID] = Animal2 .[AnimalId]
     INNER JOIN [Genes] 
           ON [CreatureCombos].[ComboGeneID] = [Genes].[GeneId] 



回答2:


I think there is problem in table design.In [CreatureCombos] remove both column [NewCreatureID] and [ComboAnimalID].Add one column call AnimalID and second Column as AnimalType int( 1,2, etc)

So in this design there will only one Animal1 join and with type you can identify AnimalType.

Also if t'row there is more animaltype or category then what you will do ?

So recommended design is more flexible and open type .



来源:https://stackoverflow.com/questions/28037064/i-have-a-stored-procedure-that-needs-to-pull-info-from-the-same-table-twice-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!