我的数据库中有两个表。一个是jobs
,另一个是type_of_service
,其中列case_reference
和ref_number
被绑定,这意味着对于每种情况case_reference,相同的数字出现在ref_number中并且它是唯一的并且是自动的以自定义方式增加,它们看起来像:
JOBS
==========
case_reference | customer | vessel
===============|==========|========
1311/2 | Dave | rg8
1311/3 | Billy | fjg32
1311/4 | Alex | sh599
和:
TYPE_OF_SERVICE
===============
ref_number | one | two | three | four
========================================
1311/2 |fire | | | medical
1311/3 | |foam | |
1311/4 | |foam |engine | medical
现在在我的网络应用程序中,我希望以下列方式显示搜索结果:
reference | customer | vessel | type of service
================================================
1311/2 | Dave | rg8 | fire-medical
1311/3 | Billy | fjg32 | foam
1311/4 | Alex | sh599 | foam-engine-medical
我得到的结果是:
$ records = array();
// build array of field names=============================================================================
$fields=array('customer','vessel',
'one','two','three','four');
// initialize empty array for WHERE clauses
$wheres=array();
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field) {
// get existing field value from POST, mark missing or empty value as FALSE
${$field} = isset($_POST[$field]) && trim($_POST[$field])!=''
? trim($_POST[$field]) : false;
// add to array of WHERE clauses only if value is not FALSE
if (${$field}) { $wheres[]="$field LIKE '%".${$field}."%'"; }
}
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs,services WHERE ref_number = case_reference AND ".
(!empty($wheres) ? implode(" AND ",$wheres) : '1=1').
";";
以及显示它们的方法:
<tbody>
<?php
foreach($records as $r) {
$watson = $r->case_reference;
?>
<tr>
<td><?php echo escape($r->case_reference); ?></td>
<td><?php echo escape($r->customer); ?></td>
<td><?php echo escape($r->vessel); ?></td>
<td><?php for ($i=0; $i <= $found; $i++) { echo escape(<?php echo '<pre>'.$records[$i]->one.'-'.$records[$i]->two.'-'.$records[$i]->three.'-'.
$records[$i]->four'</pre>'} ?>); ?></td>
</tr>
<?php
}
?>
</tbody>
但我遇到的问题是,当我尝试这样做时会发生以下结果:
reference | customer | vessel | type of service
================================================
1311/2 | Dave | rg8 | fire---medical-,
1311/3 | Billy | fjg32 | -foam---
1311/4 | Alex | sh599 | -foam-engine-medical-
是否有方法/功能可以实现所需的效果,而不会在表"-"
中为空单元格显示额外的type_of_service
或额外空格?
答案 0 :(得分:1)
您可以使用CONCAT_WS
mysql> SELECT CONCAT_WS(',','First name','Second name','Last Name');
-> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name');
-> 'First name,Last Name'
所以SQL查询将是
SELECT a.case_reference AS reference,
a.customer AS customer,
a.vessel AS vessel,
CONCAT_WS('-',b.one,b.two,b.three,b.four) AS types_of_service
FROM JOBS a,
TYPES_OF_SERVICE b
WHERE a.case_reference = b.ref_number;
如您所见,如果没有值,我假设该字段包含NULL
ref_number | one | two | three | four
========================================
1311/2 |fire | NULL| NULL | medical
如果不是这种情况,则需要做一些额外的工作。