0

我有 2 张桌子。

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

tblnode
-------
nodeid
personid
parentid

我想要的是一个 SQL 语句,它获取 parentid、丈夫/wifeid 和 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;

它给出了错误 #1054 - 'where 子句'中的未知列't.parentid'。

任何想法如何解决?

非常感谢,

4

4 回答 4

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
于 2011-01-28T21:49:52.150 回答
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 的最小计数。

于 2011-01-28T21:50:53.030 回答
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
于 2011-01-28T21:52:43.677 回答
0

我认为表格别名“t”在最终声明中没有被识别。您需要为联合语句返回的 set 分配一个别名,并在 select count(*) 语句中引用该别名。

于 2011-01-28T21:53:06.453 回答