我正在尝试从一个表(“SP_Cont”)获取联系信息,然后根据县代码(CID)从“Counties”表中获取实际的县名(“CTitle”)。 / p>
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,如果有一个NULL CID脚本仍然运行,但没有县标题?
干杯 ģ
答案 0 :(得分:0)
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"