What is the proper syntax in SQL Server for addressing tables?

前端 未结 7 443
-上瘾入骨i
-上瘾入骨i 2021-01-18 10:05

This seems like a fairly obvious question, but I haven\'t been able to think of the proper term for what I am trying to ask, so coming up with reference material for this ha

7条回答
  •  有刺的猬
    2021-01-18 10:11

    You are correct. Basically SQL will attempt to find the field you are looking for "my_column" in all of the tables in your FROM and JOIN sections. If however you happen to have a "my_column" in table A and in table B then you need to explicitly tell it which "my_column" you are looking for by including the table name. This goes on up the chain to dbo and databasename if you have collisions there as well.

    Most of the time you will find that people don't explicitly call out the tables a column is in unless they are joining multiple tables.

    For example I write my queries like this:

    SELECT a.field1, b.field2
    FROM tableA AS a
    INNER JOIN tableB AS b ON a.id = b.a_id
    WHERE a.id = 123
    

    Here I am using the AS to alias tableA and tableB down to more readable a and b. I could have just as easily written my query like this:

    SELECT tableA.field1, tableB.field2
    FROM tableA
    INNER JOIN tableB ON tableA.id = tableB.a_id
    WHERE tableA.id = 123
    

    Or like this, if field1 and field2 are unique to there tables, but this gets a bit confusing as to where each piece of data is coming from.

    SELECT field1, field2
    FROM tableA
    INNER JOIN tableB ON tableA.id = tableB.a_id
    WHERE tableA.id = 123
    

提交回复
热议问题