SQL加入问题

时间:2011-01-28 21:43:49

标签: sql mysql mysql-error-1054

我有2张桌子。

tblparents
----------
parentid
husbandid
wifeid 

tblnode
-------
nodeid
personid
parentid

我想要的是一个SQL语句,它获取parentid,丈夫/妻子和tblnode中parentid相等的行数。

我写了代码

SELECT t.parentid, t.spouseid, t.active, c.count FROM    
(SELECT parentid, wifeid spouseid from tblparents WHERE husbandid=1
UNION
SELECT parentid, husbandid spouseid from tblparents WHERE wifeid=1) t 
INNER JOIN 
(SELECT COUNT(*) count FROM tblnodes WHERE tblnodes.parentid=t.parentid) c;

它在'where子句'中出现错误#1054 - 未知列't.parentid'。

任何想法如何解决?

非常感谢,

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t.parentid, t.spouseid, t.active, COALESCE(c.count, 0) AS count
FROM (
    SELECT parentid, wifeid spouseid
    FROM tblparents
    WHERE husbandid = 1

    UNION

    SELECT parentid, husbandid spouseid
    FROM tblparents
    WHERE wifeid = 1
) t
LEFT JOIN (
    SELECT parentid, COUNT(*) count
    FROM tblnodes
    GROUP BY parentid
) c
    ON c.parentid = t.parentid

答案 1 :(得分:0)

如果我理解你的问题:

SELECT t.parentid, t.husbandid, t.wifeid, COUNT(*)
LEFT JOIN tblnode n
    ON n.parentid = t.parentid
GROUP BY t.parentid. t.husbandid, t.wifeid

编辑:这将返回最小数量1。

答案 2 :(得分:0)

出现语法错误。试试这个:

SELECT t.parentid, t.spouseid, t.active, c.count FROM    
(SELECT parentid, wifeid spouseid from tblparents WHERE husbandid=1
UNION
SELECT parentid, husbandid spouseid from tblparents WHERE wifeid=1) t 
INNER JOIN 
(SELECT parentid, COUNT(*) count
 FROM tblnodes GROUP BY parentid) c
ON c.parentid=t.parentid) c ;

但是,以下查询的效果会更好:

SELECT t.parentid, t.wifeid spouseid, t.active, COUNT(t.parentid) CNT
FROM tblparents t LEFT JOIN tblnode c
    ON t.parentid = c.parentid
GROUP BY t.parentid. t.wifeid, t.active

答案 3 :(得分:0)

我认为表别名“t”未在最终声明中被识别。您需要为unioned语句返回的set指定别名,并在select count(*)语句中引用该别名。