I'm analysing a rather horrible legacy database/codebase, trying to reduce server load by combining queries into joins (including an email alert cron job that typically invokes well over a million separate queries).
SELECT * FROM class_alerts_holding ah INNER JOIN class_listings l ON l.id = ah.lid INNER JOIN class_users u ON u.id = ah.uid LEFT JOIN class_prodimages pi ON pi.pid = ah.lid
This spits out 120 columns...
aid | id | lid | uid | oid | catName | searchtext | alertfreq | listType | id | owner | title | section | shortDescription | description | featured | price | display | hitcount | dateadded | expiration | url | notified | searchcount | repliedcount | pBold | pHighlighted | notes | ...
To assist my analysis of how to construct the new queries it would be awesome if I could prefix the columns in the result with the table they came from in the JOIN e.g.
class_alerts_holding.aid | class_alerts_holding.id | class_listings.lid | ...
Is there a way to achieve this?
A self join is a join in which a table is joined with itself (which is also called Unary relationships), especially when the table has a FOREIGN KEY which references its own PRIMARY KEY.
A LEFT JOIN will always include the rows from the LEFT table, even if there are no matching rows in the table it is JOINed with. When there is no match, the corresponding rows will use NULL to represent the missing values from the second table.
SQL FULL OUTER JOIN Example Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether the other table matches or not.
An INNER JOIN is such type of join that returns all rows from both the participating tables where the key record of one table is equal to the key records of another table. This type of join required a comparison operator to match rows from the participating tables based on a common field or column of both the tables.
You could
select ah.*, l.*, u.*, pi.* from ...
then the columns will be returned ordered by table at least.
For better distinction between every two sets of columns, you could also add "delimiter" columns like this:
select ah.*, ':', l.*, ':', u.*, ':', pi.* from ...
(Edited to remove explicit aliases as unnecessary, see comments.)
You could name the fields in your query and give them aliases:
SELECT ah.whateverfield1 AS 'ah_field1', ah.whateverfield2 AS 'ah_field2', l.whateverfield3 AS 'l.field3', [....] FROM class_alerts_holding ah INNER JOIN class_listings l ON l.id = ah.lid INNER JOIN class_users u ON u.id = ah.uid LEFT JOIN class_prodimages pi ON pi.pid = ah.lid
Its a bit of work to manually set up if you have that many fields, but you can simplify this with this query...
SHOW FULL FIELDS FROM your_table_name;
...and a good text editor and copy & paste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With