Adem Natural
Adem Natural

Reputation: 105

Getting the filenames record

I have case to get filenames from table foto for the firts table

tb_induk
----------------
id_induk    | nomor_induk  | id_burung | hen     |   cock
25          |   IND003     |     2     |  91442  |  30441
26          |   IND004     |     2     |  10464  |  40020

note : column "hen" and "cock" is "id_data" from birds

second table:

tb_foto
----------------------
id_foto   | id_data | filename
566       |91442    |4b584a8cd6cb98d4b4d9614abb223034.JPG
567       |91442    |b526318215b5c12bf79b3284d8bd5db7.JPG
568       |30441    |4db159080e0cefb4fd9a2862502ab0f5.JPG
570       |10464    |4216d01abb3bdce90bd72e40ef1d593b.JPG
571       |40020    |6c5b28bffd79fc661f44733c04d12446.JPG

The query is:

Query
-----------------------
   "select 
tb_induk.id_induk as id_induk, 
tb_induk.nomor_induk as nomor_induk, 
case WHEN tb_foto.id_data=tb_induk.Hen THEN tb_foto.filename END as filenamehen,
case WHEN tb_foto.id_data=tb_induk.Cock THEN tb_foto.filename END as filenamecock 
from tb_induk INNER JOIN tb_foto ON 
tb_induk.Hen=tb_foto.id_data || tb_induk.Cock=tb_foto.id_data 
where id_burung=$id_burung GROUP BY tb_induk.id_induk"

Result

Result
------------------------------
id_induk    | nomor_induk  | id_burung | hen                                  |   cock
    25      |   IND003     |     2     | 4216d01abb3bdce90bd72e40ef1d593b.JPG |  NULL
    26      |   IND004     |     2     |  NULL                                |  207b21895c556bc5fada1ead8ec34d06.JPG

Upvotes: 1

Views: 33

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

I think you can just join tb_foto twice to pull in the filenames for hens and cocks, for each tb_induk value:

SELECT t1.tb_induk,
       t1.nomor_induk,
       t1.id_burung,
       COALESCE(tf1.filename, 'NA') AS hen,
       COALESCE(tf2.filename, 'NA') AS cock
FROM tb_induk t1
LEFT JOIN tb_foto tf1
    ON t1.hen = tf1.id_data
LEFT JOIN tb_foto tf2
    ON t1.cock = tf2.id_data

Upvotes: 1

Related Questions