开发者

SQL - Why isn't there a way to SELECT ALL, except this column

开发者 https://www.devze.com 2023-02-14 14:39 出处:网络
My general question is that I want to select all columns from a left join, and I don\'t need to know the ID that joins the two tables. I know that it is unnecessary to select all, but since you need a

My general question is that I want to select all columns from a left join, and I don't need to know the ID that joins the two tables. I know that it is unnecessary to select all, but since you need all the fields except the ids, why isn't there a shorter way to: SELECT * except "this column", i feel like the action time should be shorter by doing the reverse way?

T1:
aID,
c1,
c2,
c3,
c4

t2:
aID,
c1,
c2,
c3,
c4

Select * from t1 left join t2 on t1.aid = t2.aid

result: t1:aid, c1, c2, c3, c4, aid, c1, c2 ,c3 ,c4

instead of selecting each of the columns that I want, I just want to select all exce开发者_如何学JAVApt "aid".


SELECT * is a shorthand that's useful for quickly prototyping a query, but is strongly not recommended for production code (outside of EXISTS expressions) - if there are any schema changes, then whatever is consuming the results of the query will get unexpected columns appearing. Similarly, your requested form would have the same issue.

Once you've shaped your query appropriately (gotten joins correct, etc), you should go back to your SELECT clause and explicitly list those columns you actually want to retrieve. Retrieving more columns than you need (including unexpected new ones) may cause SQL Server to have to use a less efficient plan, or retrieve massive amounts of data that the consumer is never going to use.


I'm not too sure that's really possible. You might want to look at a dynamic query in this instance, where all columns from the two joining tables will be included in the query, except the foreign key.

You can even consider writing a Procedure of sorts that accepts parameters for @Table1, @Table2, @PK, @FK and then build up the query dynamically based on the parameters supplied.


Premature optimization is the root of all evil (or at least most of it) in programming. – Donald E. Knuth

Why do you care if the id column is returned or not?

Also, yes this might be a bit of an oversight in the SQL design.


For the same reason that SELECT * is not a good idea. It can be annoying at best and dangerous at worst to use SELECT * in your queries. If the table or datasource you are querying changes then it can have unexpected behaviour.


Sounds like what you are looking for is NATURAL JOIN.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号