2016-12-03 13 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