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

老子叫甜甜 提交于 2020-01-06 03:35:41

问题


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 except "aid".


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


Sounds like what you are looking for is NATURAL JOIN.



来源:https://stackoverflow.com/questions/5152695/sql-why-isnt-there-a-way-to-select-all-except-this-column

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