问题
I hope I can explain myself good, so I have 2 tables with one-to-many connection (TableA and TableB). Now, TableB has a column with a foreign key form TableA, and an ID (foreign key) to a third TableC. Now usually 2 to 3 rows share the same FK from TableA and this are my possible scenarios:
- All rows with same FK_TableA have the same FK_TableC
- All rows with same FK_TableA have NULL for FK_TableC
All rows with same FK_TableA have either NULL or same FK_TableC like so:
TableB ---------------------------- |ID| FK_TableA | FK_TableC | ---------------------------- |1 | 123 | 321 | |2 | 123 | 321 | |3 | 123 | NULL | ----------------------------
So 2 rows can't have the same FK_TableA and different FK_TableC it's either the same or on has it an another is null or all null.
Now my question is how can I select the FK_TableC distinctively based on FK_TableA, in a way so if any row with FK_TableA has a value (not null) select that value else null and join the results to TableA?
I have been trying with JOINS and FROM - WHERE but I always either lose or double rows. So from the table above I would need to select like so:
TmpTable
-------------------------
| FK_TableA | FK_TableC |
-------------------------
| 123 | 321 | => From Above
| 124 | NULL | => If all FK_TableC ware null
| 125 | 325 | => If at least one or all FK_TableC ware 325
-------------------------
Thank you in advance.
回答1:
I found my answer, thanks to the answer to this question Easiest way to eliminate NULLs in SELECT DISTINCT?, maybe I shouldn't have rushed with asking it. My query looks something like this:
SELECT A.ID, A.NAME, C.ID_D FROM TABLE TableA A
LEFT JOIN (SELECT DISTINCT FK_TableA, MAX(FK_TableC) AS ID_C FROM TableB
GROUP BY (FK_TableA)) B ON B.FK_TableA = A.ID
LEFT JOIN TableC C ON C.ID = B.ID_C
来源:https://stackoverflow.com/questions/37523347/select-the-non-null-value-if-exists-else-null-but-always-select-the-row