Labels

Android (1) bash (2) boost (2) C (34) C++ (2) cheatsheet (2) CLion (6) css (3) Debian (33) DL (17) Docker (1) Dreamweaver (2) Eclipse (3) fail2ban (4) git (5) GitHub (4) Hacking (3) html (8) http (1) iOS (1) iPad (1) IRC (1) Java (30) javascript (3) Linux (164) Mac (19) Machine Learning (1) mySQL (47) Netbeans (4) Networking (1) Nexus (1) OpenVMS (6) Oracle (1) Pandas (3) php (16) Postgresql (8) Python (9) raid (1) RedHat (14) Samba (2) Slackware (45) SQL (14) svn (1) tar (1) ThinkPad (1) Virtualbox (3) Visual Basic (1) Visual Studio (1) Windows (2)

Sunday 10 May 2020

Alternative methods of joining results from two tables


If we are wanting to pull information from two different tables that are linked in some way, the conventional way of doing this is as follows:

SELECT  table1.item, table2.item
FROM table1 JOIN table2 ON table1.item = table2.item;

However an alternative is to use the following;

SELECT  table1.item, table2.item
FROM table1, table2
WHERE table1.item = table2.item;


If we use the following as an example;




We can see that we have two tables, log and users.

users has a PK username and log has a PK id
log also has a number of FKs but the one we are interested in here is username which of course relates/points to the username field in users.

So with the above in mind, if we are looking to query the information in the log table then we can do so with the following;

SELECT id, fault_occured, machine, `module`, fault, responsibility,
resolved, username, fault_resolved FROM log;

But let's say we want to see the realname instead of the username. We then need to grab the realname from the users table and we can do this in one of two ways;

Using a JOIN in either of the following;

SELECT id, fault_occured, machine, `module`, fault, responsibility,
resolved, users.realname, fault_resolved
FROM log JOIN users ON log.username=users.username ORDER BY fault_occured DESC;

the below is the same only instead of using JOIN ON, we use JOIN WHERE

SELECT id, fault_occured, machine, `module`, fault, responsibility,
resolved, users.realname, fault_resolved
FROM log JOIN users WHERE log.username=users.username;


or alternatively just using plain old WHERE with no JOIN

SELECT id, fault_occured, machine, `module`, fault, responsibility,
resolved, users.realname, fault_resolved
FROM log,users WHERE log.username=users.username;



No comments:

Post a Comment

Note: only a member of this blog may post a comment.