I have three tables with the middle table is the many-to-many resulting table (AB). What is the most efficient SQL statement to get:
1 - All records from the two other tables (Table A and Table B) regardless if there are matching data in Table AB 2 - Each record should show true if the two tables are linked (i.e. there is a rercord in the many-many resulting table) or false if it is null
Basically I want to display a matrix table with first column displaying all records from table A, and the first row showing all recrods table B, then the intersecting cells should be ticked if there a matching record in table AB.
If I do not mind parsing the final data set programatically if I have to
Thank you
Try something like this:
SELECT A.id AS "A id", B.id AS "B id", AB.id IS NOT NULL AS "Match"
FROM A
JOIN B
LEFT JOIN AB ON A.id = A_id AND B.id = B_id
The SQL Fiddle also has an ORDER BY
clause.