如何在组sql

时间:2016-12-03 15:20:08

标签: php mysql

我的问题是如何将查询group_concat()添加到原始查询中?

这是我原来的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>

1 个答案:

答案 0 :(得分: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