Can you include the columns of two separate tables in the result of a sql query?
I am trying to order the results of a sql query of one table using the column of another table. Is it possible to include this column from a different table in my results?
For example, this query uses an inner join to order items in the Children table based on the Parent table's column "dateReceived":
SELECT c.* FROM children c INNER JOIN parent p ON c.parent_id = p.parent_id ORDER BY dateReceived ASC;
The view would be more helpful if it could somehow include the "dateReceived" column from the Parent table in the results. I am new to SQL, is this possible?
Yes all you need to do is add that column to your
SELECTlist via the correct alias like so:
SELECT p.dateReceived, c.* FROM children c INNER JOIN parent p ON c.parent_id = p.parent_id ORDER BY p.dateReceived ASC;
Notice that the alias
childrentable in the context of this query.
Also you shouldn't use
SELECTlist (most times) because it is bad practice for readability, maintainability, performance reasons, and is error prone. Instead you should explicitly list out each column that you want returned. For example:
SELECT p.dateReceived, c.child_id, c.parent_id, c.firstName, c.gender, c.age, c.shoe, c.notes FROM children c INNER JOIN parent p ON c.parent_id = p.parent_id ORDER BY p.dateReceived ASC;