2016-12-03 14 views
-1

我的問題是我該如何將查詢group_concat()添加到我的原始查詢中?如何在組中使用group_concat()函數sql

這是我原來的SQL:

select * 
from info 
join crew_documents_table on info.id = crew_documents_table.document_crew_id 
join crew_rank on info.crew_rank = crew_rank.crew_rank_id 
where crew_rank in ('1','2','3') and crew_status = '$crew_status' 
and doc_type in ('1','2') and vessel = '$vessel_name' 
and date_issue in (
    select max(date_issue) 
    from crew_documents_table 
    where crew_documents_table.document_crew_id = info.id 
) 

,我想在裏面添加group_concat()功能是這樣的:

SELECT document_crew_id, 
GROUP_CONCAT(doc_number) as document_number, 
GROUP_CONCAT(date_issue) as date_issued, 
GROUP_CONCAT(date_expiry) as date_expired, 
GROUP_CONCAT(place_of_issue) as place_issued 
from crew_documents_table group by document_crew_id 

,這是我從查詢得到的紀錄:

<td><?php if($row['doc_type'] == '1') { echo "$doc_number"; } ?></td> 
<td><?php if($row['doc_type'] == '1') { echo "$date_issue"; } ?></td> 
<td><?php if($row['doc_type'] == '1') { echo "$date_expiry"; } ?></td> 
<td><?php if($row['doc_type'] == '1') { echo "$place_of_issue"; } ?></td> 
<td><?php if($row['doc_type'] == '2') { echo "$doc_number"; } ?></td> 
<td><?php if($row['doc_type'] == '2') { echo "$doc_number"; } ?></td> 
<td><?php if($row['doc_type'] == '2') { echo "$doc_number"; } ?></td> 
<td><?php if($row['doc_type'] == '2') { echo "$doc_number"; } ?></td> 
+2

你的問題是什麼?你有錯誤? ..錯誤的結果?沒有結果? – scaisEdge

+0

我會編輯。對不起,如果它不清楚。我的問題是如何即時添加查詢group_concat()抱歉 –

回答

0

只要更改*與列和添加適當的組由

select 
    document_crew_id, 
    GROUP_CONCAT(doc_number) as document_number, 
    GROUP_CONCAT(date_issue) as date_issued, 
    GROUP_CONCAT(date_expiry) as date_expired, 
    GROUP_CONCAT(place_of_issue) as place_issued 
    from info join crew_documents_table on info.id = crew_documents_table.document_crew_id 
    join crew_rank on info.crew_rank = crew_rank.crew_rank_id 
    where crew_rank in ('1','2','3') and crew_status = '$crew_status' 
    and doc_type in ('1','2') and vessel = '$vessel_name' 
    and date_issue in (select max(date_issue) 
    from crew_documents_table 
    where crew_documents_table.docume