SQL JOIN Flashcards
How to make CROSS JOIN connection between 2 tables?
SELECT * FROM Customers CROSS JOIN Categories;
How to make CROSS JOIN connection and show only 2 columns from each table?
SELECT cust.CustomerName, categor.CategoryName FROM Customers AS cust CROSS JOIN Categories AS categor;
How to make INNER JOIN connection?
SELECT * FROM Products INNER JOIN Categories ON Categories.CategoryID = Products.CategoryID;
How to make NATURAL JOIN connection?
# we use natural join if we have the same fields in two tables SELECT * FROM Products NATURAL JOIN Categories;
How to make LEFT OUTER JOIN?
SELECT * FROM Customers
LEFT OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;
How to make RIGHT OUTER JOIN?
SELECT * FROM Orders
RIGHT OUTER JOIN Employees
ON Orders.EmployeeID = Employees.EmployeeID;
How to combine result of 2 selects into one? ( sum of 2 tables)
# all cities from the first table + all cities from another table # values will be UNIQ SELECT City FROM Customers UNION SELECT City FROM Suppliers;
How to combine result of 2 selects into one with duplication? ( sum of 2 tables)
# all cities from the first table + all cities from another table # values won't be UNIQ SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers;
How to return data from the first request which are also included in another request?
SELECT City FROM Customers
INTERSECT
SELECT City FROM Suppliers;
How to return data from the first request but without the data from the second request?
SELECT City FROM Customers
EXCEPT
SELECT City FROM Suppliers;
How to create nested join in rails?
Building ( has_many :floors)
Floor ( has many :cabinets)
Cabinet ( belongs_to floor)
to get access from cabinet to building
Cabinet.joins(:floors => buildings)
you can nest more than one join and do it in 2 directions
AvailableCurrency.joins(scheme: {companies: :employees}).where(‘employees.id = 1’)
How to return data from joined table?
> > cities = RefCity.joins(:country).select(‘ref_cities.id, ref_cities.name’)
cities.first.id # city id
cities.first.name # city name