Mysql内部查询不起作用

时间:2009-10-05 05:51:42

标签: sql mysql

    $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中编写它时,它会显示错误。帮助

1 个答案:

答案 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,并添加外键约束。