I've got three tables in a MySql database that I'm joining in a query to get id/value pairs.
| A | B | C |
| -------- |--------------|---------------|
| id | id | id |
| name | fooId | attributeId |
| desc | value | displayIndex |
| ... | attributeId | ... |
What I have now is:
SELECT C.id, B.value
FROM A, B, C
WHERE A.id = B.attributeId
AND A.id = C.attributeId
AND B.fooId = 25
ORDER BY C.displayIndex
So basically we're joining B and C through A. It used to be that an entry in the C table had to have a corresponding (parent) entry in the A table. However, that will no longer be the case. The C table will still be MOSTLY controlled by the A table, however, there are some instances when we need a stand alone (always on) entry in the C table.
EDIT
I want all the records from B and C that match on attributeId but I also want any record where C.attributeId = -1. Can someone help with what I'd need to do with this query?
Edit #2
Based on feedback and suggestions you guys have made and some googling I now have this:
(SELECT C.id, B.value, C.displayIndex
FROM B, C
WHERE B.attributeId = C.attributeId
AND B.fooId = 25)
UNION
(SELECT C.id, null, C.displayIndex
FROM C
WHERE C.attributeId = -1)
ORDER BY 3
Is there a better what to do this? Are there any problems with UNION?
I've updated my answer to address the edits from the OP.
This will return all records where the attributeId for tables B and C match,
with B.fooId = 25, OR C.attributeId = -1.
When C.attributeId = -1 and there is no match in table B, NULL will be returned in place of B.Value, which appears to be acceptable based on the Edit #2 from the OP
SELECT C.Id, B.Value, C.displayIndex
FROM C
LEFT JOIN B ON C.attributeId = B.attributeId
WHERE B.fooId = 25
OR C.attributeId = -1
ORDER BY C.DisplayIndex ASC
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