조인은 게으른 사람들을위한 것입니까?
최근에 JOIN (SQL)이 쓸모 없다고 주장한 다른 개발자와 토론을했습니다. 이것은 기술적으로 사실이지만 조인을 사용하는 것이 코드에서 여러 요청 및 링크 테이블 (C # 또는 Java)을 만드는 것보다 덜 효율적이라고 덧붙였습니다.
그에게 참여는 성능에 관심이없는 게으른 사람들을위한 것입니다. 이것이 사실입니까? 조인을 사용하지 않아야합니까?
아닙니다. 우리는 그러한 잘못된 의견을 가진 개발자를 피해야합니다.
많은 경우에 데이터베이스 조인은 DB 왕복을 피하고 DB는 인덱스를 사용하여 조인을 수행 할 수 있기 때문에 클라이언트를 통해 수행되는 것보다 몇 배 빠릅니다.
내 머리 꼭대기에서 올바르게 사용 된 조인이 동등한 클라이언트 측 작업보다 느린 단일 시나리오조차 상상조차 할 수 없습니다.
편집 : 사용자 정의 클라이언트 코드가 간단한 DB 조인보다 효율적으로 작업을 수행 할 수있는 드문 경우가 있습니다 (meriton의 의견 참조). 그러나 이것은 예외입니다.
동료가 SQL이없는 문서 데이터베이스 또는 키 값 저장소와 잘 어울리는 것처럼 들립니다. 그 자체로는 매우 훌륭한 도구이며 많은 문제에 적합합니다.
그러나 관계형 데이터베이스는 세트 작업에 최적화되어 있습니다. 많은 왕복 여행보다 훨씬 효율적인 조인을 기반으로 데이터를 쿼리하는 방법에는 여러 가지가 있습니다. 이것이 바로 rdbms의 다재다능 함입니다. nosql 스토어에서도 동일한 결과를 얻을 수 있지만, 종종 각기 다른 쿼리 특성에 적합한 별도의 구조를 구축하게됩니다.
한마디로 : 동의하지 않습니다. RDBMS에서 조인은 기본 입니다. 사용하지 않는 경우 RDBMS로 사용하지 않는 것입니다.
글쎄, 그는 일반적인 경우에 틀렸다.
데이터베이스는 옵티 마이저 힌트, 테이블 인덱스, 외래 키 관계 및 기타 데이터베이스 공급 업체별 정보를 통해 다양한 방법을 사용하여 최적화 할 수 있습니다.
아닙니다.
데이터베이스는 특별히 데이터 세트를 조작하도록 설계되었습니다 (분명히 ....). 따라서이 작업을 수행하는 데 매우 효율적입니다. 그는 본질적으로 자신의 코드에서 수동 조인을 수행함으로써 작업을 위해 특별히 설계된 무언가의 역할을 인수하려고합니다. 그의 코드가 데이터베이스의 코드만큼 효율적일 가능성은 매우 먼 것입니다.
조인없이 따로 데이터베이스 사용의 요점은 무엇입니까? 텍스트 파일 만 사용할 수도 있습니다.
"게으른"이 적은 코드를 작성하려는 사람들로 정의되면 동의합니다. "게으른"이 도구가 자신이 잘하는 일을하도록하려는 사람들로 정의된다면, 나는 동의한다. 그가 단지 Larry Wall (좋은 프로그래머의 속성과 관련하여)에 동의한다면, 나는 그에게 동의합니다.
음, 조인은 관계형 데이터베이스가 테이블을 서로 관련시키는 방법입니다. 그가 무엇을 받고 있는지 잘 모르겠습니다.
데이터베이스를 여러 번 호출하는 것이 한 번의 호출보다 더 효율적일 수있는 방법은 무엇입니까? 또한 SQL 엔진은 이러한 종류의 작업을 수행하는 데 최적화되어 있습니다.
동료가 SQL을 배우기에는 너무 게으른 것 같습니다.
그렇습니다.
성능 때문에 C # 대신 C ++를 사용해야합니다. C #은 게으른 사람들을위한 것입니다.
아니, 아니. 성능 때문에 C ++ 대신 C를 사용해야합니다. C ++는 게으른 사람들을위한 것입니다.
아니, 아니. 성능 때문에 C 대신 어셈블리를 사용해야합니다. C는 게으른 사람들을위한 것입니다.
네, 농담입니다. 조인없이 더 빠른 프로그램을 만들 수 있으며 조인없이 더 적은 메모리를 사용하여 프로그램을 만들 수 있습니다. 그러나 많은 경우 개발 시간이 CPU 시간 및 메모리보다 중요합니다. 약간의 성능을 포기하고 인생을 즐기십시오. 약간의 성능을 위해 시간을 낭비하지 마십시오. "왜 당신은 당신의 장소에서 사무실까지 직진 고속도로를 만들지 않습니까?"
"이것은 기술적으로 사실입니다."-마찬가지로 SQL 데이터베이스도 쓸모가 없습니다. 많은 CSV 파일을 사용하여 코드로 서로 연관 시켜서 동일한 결과를 얻을 수있을 때 데이터베이스를 사용하는 데있어 요점은 무엇입니까? 도대체 모든 게으른 사람들을위한 것입니다. 하드웨어에서 바로 기계 코드 프로그래밍으로 돌아가 봅시다! ;)
또한 그의 주장은 가장 복잡한 경우를 제외하고는 모두 사실이 아닙니다. RDBMS는 JOIN을 빠르게 하기 위해 크게 최적화되어 있습니다. 관계형 데이터베이스 관리 시스템?
내가 일한 마지막 회사는 SQL 조인도 사용하지 않았습니다. 대신에 그들은이 작업을 수평으로 확장하도록 설계된 응용 계층으로 옮겼습니다. 이 설계의 근거는 데이터베이스 계층에서의 작업을 피하는 것입니다. 일반적으로 병목 현상이 발생하는 데이터베이스입니다. 데이터베이스보다 응용 프로그램 계층을 복제하는 것이 더 쉽습니다. 다른 이유가있을 수 있습니다. 그러나 이것은 내가 지금 기억할 수있는 것입니다.
예, 응용 프로그램 계층에서 수행 된 조인이 데이터베이스에서 수행 한 조인에 비해 비효율적이라는 데 동의합니다. 더 많은 네트워크 통신.
SQL 조인을 피하기 위해 열심히 노력하고 있지는 않습니다.
조인없이 주문 항목을 주문과 어떻게 연관시킬 것인가? 이것이 관계형 데이터베이스 관리 시스템의 요점입니다. 조인이 없으면 관계형 데이터가 없으며 텍스트 파일을 사용하여 데이터를 처리 할 수도 있습니다.
그는 개념을 이해하지 못하는 것처럼 들리므로 개념을 쓸모없는 것처럼 보이려고합니다. 그는 엑셀이 데이터베이스 응용 프로그램이라고 생각하는 사람과 같은 유형입니다. 그를 바보로 때리고 데이터베이스에 대해 더 읽어 보라고한다. 여러 연결을 만들고 데이터를 가져오고 C #을 통해 데이터를 병합하는 것은 잘못된 방법입니다.
"SQL의 조인은 쓸모가 없습니다"라는 문장의 논리를 이해하지 못합니다. 작업하기 전에 데이터를 필터링하고 제한하는 것이 유용한가요? 다른 응답자들이 이것이 데이터베이스 엔진이하는 일이라고 말했듯이, 그들이 잘하는 것이되어야합니다.
아마도 게으른 프로그래머는 친숙한 기술을 고수하고 비 기술적 인 이유로 다른 가능성을 피할 것입니다.
나는 당신에게 결정을 내립니다.
송장 레코드가있는 테이블과 송장 개별 항목 레코드가있는 관련 테이블을 예로 들어 보겠습니다. 클라이언트 의사 코드를 고려하십시오.
for each (invoice in invoices)
let invoiceLines = FindLinesFor(invoice)
...
10 개의 송장을 가진 10 개의 송장이있는 경우이 코드는 1 백만 표에서 10 개의 송장을 조회하며 10 만 번 수행합니다. 테이블 크기가 증가하면 선택 조작 수가 증가 하고 각 선택 조작 비용이 증가합니다.
컴퓨터가 빠르면 레코드가 수천 개 이하인 경우 두 방법간에 성능 차이를 느끼지 못할 수 있습니다. 비용 증가는 선형적인 것보다 많기 때문에 레코드 수가 증가함에 따라 (예 : 수백만으로) 차이를 느끼기 시작하고 데이터 세트의 크기가 커짐에 따라 그 차이는 용납 될 수 없게됩니다.
The join, however. will use the table's indexes and merge the two data sets. This means that you're effectively scanning the second table once rather than randomly accessing it N times. If there's a foreign key defined, the database already has the links between the related records stored internally.
Imagine doing this yourself. You have an alphabetical list of students and a notebook with all the students' grade reports (one page per class). The notebook is sorted in order by the students' names, in the same order as the list. How would you prefer to proceed?
- Read a name from the list.
- Open the notebook.
- Find the student's name.
- Read the student's grades, turning pages until you reach the next student or the last page.
- Close the notebook.
- Repeat.
Or:
- Open the notebook to the first page.
- Read a name from the list.
- Read any grades for that name from the notebook.
- Repeat steps 2-3 until you get to the end
- Close the notebook.
Sounds like a classic case of "I can write it better." In other words, he's seeing something that he sees as kind of a pain in the neck (writing a bunch of joins in SQL) and saying "I'm sure I can write that better and get better performance." You should ask him if he is a) smarter and b) more educated than the typical person that's knee deep in the Oracle or SQL Server optimization code. Odds are he isn't.
He is most certainly wrong. While there are definite pros to data manipulation within languages like C# or Java, joins are fastest in the database due to the nature of SQL itself.
SQL keeps detailing statistics regarding the data, and if you have created your indexes correctly, can very quickly find one record in a couple of million. Besides the fact that why would you want to drag all your data into C# to do a join when you can just do it right on the database level?
The pros for using C# come into play when you need to do something iteratively. If you need to do some function for each row, it's likely faster to do so within C#, otherwise, joining data is optimized in the DB.
I will say that I have run into a case where it was faster breaking the query down and doing the joins in code. That being said, it was only with one particular version of MySQL that I had to do that. Everything else, the database is probably going to be faster (note that you may have to optimize the queries, but it will still be faster).
I suspect he has a limited view on what databases should be used for. One approach to maximise performance is to read the entire database into memory. In this situation, you may get better performance and you may want to perform joins if memory for efficiency. However this is not really using a database, as a database IMHO.
No, not only are joins better optimized in database code that ad-hoc C#/Java; but usually several filtering techniques can be applied, which yields even better performance.
He is wrong, joins are what competent programmers use. There may be a few limited cases where his proposed method is more efficient (and inthose I would probably be using a Documant database) but I can't see it if you have any deceent amount of data. For example take this query:
select t1.field1
from table1 t1
join table2 t2
on t1.id = t2.id
where t1.field2 = 'test'
Assume you have 10 million records in table1 and 1 million records in table2. Assume 9 million of the records in table 1 meet the where clause. Assume only 15 of them are in table2 as well. You can run this sql statement which if properly indexed will take milliseconds and return 15 records across the network with only 1 column of data. Or you can send ten million records with 2 columns of data and separately send another 1 millions records with one column of data across the network and combine them on the web server.
Or of course you could keep the entire contents of the database on the web server at all times which is just plain silly if you have more than a trivial amount of data and data that is continually changing. If you don't need the qualities of a relational database then don't use one. But if you do, then use it correctly.
I've heard this argument quite often during my career as a software developer. Almost everytime it has been stated, the guy making the claim didn't have much knowledge about relational database systems, the way they work and the way such systems should be used.
Yes, when used incorrectly, joins seem to be useless or even dangerous. But when used in the correct way, there is a lot of potential for database implementation to perform optimizations and to "help" the developer retrieving the correct result most efficiently.
Don't forget that using a JOIN
you tell the database about the way you expect the pieces of data to relate to each other and therefore give the database more information about what you are trying to do and therefore making it able to better fit your needs.
So the answer is definitely: No, JOINS
aren't useless at all!
This is "technically true" only in one case which is not used often in applications (when all the rows of all the tables in the join(s) are returned by the query). In most queries only a fraction of the rows of each table is returned. The database engine often uses indexes to eliminate the unwanted rows, sometimes even without reading the actual row as it can use the values stored in indexes. The database engine is itself written in C, C++, etc. and is at least as efficient as code written by a developer.
Unless I've seriously misunderstood, the logic in the question is very flawed
If there are 20 rows in B for each A, a 1000 rows in A implies 20k rows in B. There can't be just 100 rows in B unless there is many-many table "AB" with 20k rows with the containing the mapping.
So to get all information about which 20 of the 100 B rows map to each A row you table AB too. So this would be either:
- 3 result sets of 100, 1000, and 20k rows and a client JOIN
- a single JOINed A-AB-B result set with 20k rows
So "JOIN" in the client does add any value when you examine the data. Not that it isn't a bad idea. If I was retrieving one object from the database than maybe it makes more sense to break it down into separate results sets. For a report type call, I'd flatten it out into one almost always.
In any case, I'd say there is almost no use for a cross join of this magnitude. It's a poor example.
You have to JOIN somewhere, and that's what RDBMS are good at. I'd not like to work with any client code monkey who thinks they can do better.
Afterthought:
To join in the client requires persistent objects such as DataTables (in .net). If you have one flattened resultset it can be consumed via something lighter like a DataReader. High volume = lot of client resources used to avoid a database JOIN.
참고URL : https://stackoverflow.com/questions/5595418/joins-are-for-lazy-people
'IT' 카테고리의 다른 글
“ArrayAdapter를 사용하려면 리소스 ID가 TextView 여야합니다.”xml 문제 (0) | 2020.05.27 |
---|---|
C #에서 정수를 이진수로 변환 (0) | 2020.05.27 |
.equals ()를 생성 할 때 instanceof보다 getClass ()를 선호하는 이유는 무엇입니까? (0) | 2020.05.27 |
webpack dev 서버를 포트 80 및 0.0.0.0에서 실행하여 공개적으로 액세스 할 수있게하는 방법은 무엇입니까? (0) | 2020.05.27 |
Perl에서 부동 소수점 숫자를 어떻게 반올림합니까? (0) | 2020.05.27 |