$sql= "select
tblservergroup.id,
tblservergroup.groupname,
if(tblservergroup.defserverpaid='0', '0', select concat(tblservers.ipaddress, ' (', tblservers.name, ')' ) as defaultserverpaiddesc from tblservers where tblservers.id=tblservergroup.defserverpaid),
if(tblservergroup.defserverfree='0', '0', select concat(tblservers.ipaddress, ' (', tblservers.name, ')' ) as defaultserverfreedesc from tblservers where tblservers.id=tblservergroup.defserverfree),
tblservergroup.note
from tblservergroup
";
这个类似的概念可以在MSSQL中完成,但是当我在mysql中编写它时,它会显示错误。帮助
答案 0 :(得分:1)
如果你坚持子查询,你可以这样做:
SELECT
tblservergroup.id,
tblservergroup.groupname,
tblservergroup.note,
IF(defserverpaid='0', '0', (SELECT concat(ipaddress, ' (', name, ')') FROM tblservers WHERE id=defserverpaid)) AS defaultserverpaiddesc,
IF(defserverfree='0', '0', (SELECT concat(ipaddress, ' (', name, ')') FROM tblservers WHERE id=defserverfree)) AS defaultserverfreedesc
FROM
tblservergroup
我建议改为使用LEFT JOIN
:
SELECT
tblservergroup.id,
tblservergroup.groupname,
tblservergroup.note,
IF(defserverpaid='0', '0', concat(ts1.ipaddress, ' (', ts1.name, ')')) as defaultserverpaiddesc
IF(defserverfree='0', '0', concat(ts2.ipaddress, ' (', ts2.name, ')')) as defaultserverfreedesc
FROM
tblservergroup
LEFT JOIN tblservers ts1 ON ts1.id=defserverpaid
LEFT JOIN tblservers ts2 ON ts2.id=defserverfree
理想情况下,还会在NULL
/ 0
中存储defserverpaid
而不是defserverfree
,并添加外键约束。