In the returned results on a query to a 'Links' table I want to also add an extra column that shows a 'DisplayName' value that is selected from a JOIN
conditional on the value of the 'toTable' per row. In addition sometimes that 'DisplayName' value is the result of a concatenation of columns.
My question is how do I do this?
I can write seperate queries and combine with UNION ALL
though I wonder if there is a conditional way to do it
Each entry in the 'Links' table describes links between a pair of entries in two tables (of a possible 3 or more tables).
Links Table:
| LinkID | fromTable | fromID | toTable | toID |
| 1 | A | 1 | B | 1 |
| 2 | A | 1 | C | 2 |
| 3 | B | 1 | C | 1 |
| 4 | C | 1 | A | 1 |
Query results I want: WHERE Links.fromTable = 'A' OR Links.fromTable = 'C' for example
| LinkID | fromTable | fromID | toTable | toID | DisplayName |
| 1 | A | 1 | B | 1 | Some Title |
| 2 | A | 1 | C | 2 | Loud-Quack |
| 4 | C | 1 | A | 1 | Linus |
3 Tables with different Columns:
Table A:
| ID | Name |
| 1 | Linus |
-
Table B:
| ID | Title |
| 1 | some title |
-
Table C:
| ID | CategoryA | CategoryB |
| 1 | Bark | Softly |
| 2 | Quack | Loud |
-
This is how I am doing this will UNION ALL
which is not very flexible:
EDIT: actually i think the below is wrong, i am looking at this now:
SELECT Links.*, A.Name AS DisplayName
FROM Links
JOIN A ON Links.toID = A.ID
WHERE Links.fromType IN ('A') AND Links.toType IN ('B')
UNION ALL
SELECT Links.*, CONCAT(C.CategoryB,'-',C.CategoryA) AS DisplayName
FROM Links
JOIN C ON Links.toID = C.ID
WHERE Links.fromType IN ('A') AND Links.toType IN ('C')