Log in

View Full Version : [SQL] Joins, Unions and Intersects



Hypertext
17-09-2008, 11:30 PM
OK. Somebody at work tried to explain it to me like it's a venn diagram of SQL objects.

But I just didn't get it. Could somebody try to explain it in a simpler form, also could you give me an example where it would be needed. I've googled around but I've only got very confusing results, partly to it being an advanced topic coined by Tizag.

Uh, I'm supposed to have left... oh well.

Agnostic Bear
17-09-2008, 11:56 PM
Joins / left joins / right joins / inner joins are just joining stuff onto stuff

http://www.w3schools.com/Sql/sql_join.asp that is the easiest to learn.

Union is simple, it's just retrieving data from n select queries instead of 1.

SELECT `blah` FROM `table1` UNION SELECT `blah` FROM `table2`

if there was results in both table1 and table2 for field blah it would return from both, you can extend this to however many you need. You can use order by and where, but you can't use table.row (e.g ORDER BY `table2.blah`) you have to use `blah`

Intersect is the same as union but is used in mssql as far as I know.

Hypertext
18-09-2008, 12:01 AM
Joins / left joins / right joins / inner joins are just joining stuff onto stuff

http://www.w3schools.com/Sql/sql_join.asp that is the easiest to learn.

Union is simple, it's just retrieving data from n select queries instead of 1.

SELECT `blah` FROM `table1` UNION SELECT `blah` FROM `table2`

if there was results in both table1 and table2 for field blah it would return from both, you can extend this to however many you need. You can use order by and where, but you can't use table.row (e.g ORDER BY `table2.blah`) you have to use `blah`

Intersect is the same as union but is used in mssql as far as I know.

I'll read up on Joins.

Unions seems easy enough.

I think your wrong on Intersects, I thought it was something like a union, but selecting distinct values that correlate through foreign keys, then again this is why I am asking.

Agnostic Bear
18-09-2008, 12:05 AM
I'll read up on Joins.

Unions seems easy enough.

I think your wrong on Intersects, I thought it was something like a union, but selecting distinct values that correlate through foreign keys, then again this is why I am asking.

Yeah my head is pretty messed up at the minute, union executes the queries separately and just bungs everything into 1 result. intersect does the same but only returns the rows that are the same in each table.

Hypertext
18-09-2008, 12:13 AM
Oh OK. Thanks, I think I have a better understanding now.

Want to hide these adverts? Register an account for free!