我正在尝试从一个表("SP_Cont")获取联系信息,然后根据县代码(CID),从"县"表中获取实际的县名("CTitle")。
SELECT
CONCAT_WS(', ',NULLIF(SP_Cont.Address1, ''),NULLIF(SP_Cont.Address2, ''),NULLIF(SP_Cont.Address3, ''),NULLIF(SP_Cont.Address4, ''),NULLIF(SP_Cont.Address5, ''),NULLIF(SP_Cont.City, ''),NULLIF(Postcode, '')) AS Address, SP_Cont.CID, SP_Cont.RevTot,
Counties.CTitle
FROM
SP_Cont
INNER JOIN
Counties
ON
Counties.CID=SP_Cont.CID
WHERE
SP_Cont.SPCode = "26"
我想要实现的是一个看起来像这样的地址......
地址 1, 地址 2, 地址 3, 市, 县, 邮政编码。
我知道上述内容不会这样做,但至少我不必像目前那样在 PHP 页面中运行另一个查询来添加县:
if (!empty($BAPrint['CID'])) {
$CQuery = mysql_query ("SELECT CTitle FROM Counties USE INDEX (CIDT) WHERE CID = ".$BAPrint['CID']);
$CPrint = mysql_fetch_array ($CQuery);
$Address .= ", ".$CPrint['CTitle'];
}
所以它看起来像这样:
地址 1、地址2、地址 3、城市、邮政编码、县。
有没有办法获得所需的地址格式
地址1, 地址2, 地址3, 市, 县, 邮政编码。?
另一个问题是,如果SP_Cont不包含 CID 代码,则脚本将失败。有没有使用CONCAT_WS,如果有空的 CID,脚本仍然运行,但没有县头衔?
干杯G
nullif的工作方式略有不同 http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_nullif
SELECT
CONCAT_WS(', ',
nullif(SP_Cont.Address1, ''),
nullif(SP_Cont.Address2, ''),
nullif(SP_Cont.Address3, ''),
nullif(SP_Cont.Address4, ''),
nullif(SP_Cont.Address5, ''),
nullif(SP_Cont.City, ''),
nullif(Counties.CTitle, '')
nullif(Postcode, '')
) AS Address,
SP_Cont.CID, SP_Cont.RevTot
FROM SP_Cont
LEFT JOIN Counties
ON Counties.CID=SP_Cont.CID
WHERE SP_Cont.SPCode = "26"