带有比较运算符的MySQL WHERE子查询

时间:2012-08-03 16:22:16

标签: mysql sql

我试图从我们的订单表中检索客户和发票ID的列表,其中客户只有一个订单。以下SQL返回零记录,应该有几十个。如果我将有效的用户标识替换为子查询,则子查询似乎可以正常工作。我一定做错了什么,有什么帮助吗?

SELECT tblclients.id AS clientid, tblinvoices.id AS invoiceid
            FROM tblorders
            join tblinvoices ON tblorders.invoiceid = tblinvoices.id
            join tblclients ON tblorders.userid = tblclients.id
            WHERE (SELECT COUNT(*) FROM tblorders WHERE userid = tblorders.userid) = 1;

1 个答案:

答案 0 :(得分:1)

我认为你的别名有问题。尝试添加T1别名:

SELECT tblclients.id AS clientid, tblinvoices.id AS invoiceid
            FROM tblorders T1
            join tblinvoices ON T1.invoiceid = tblinvoices.id
            join tblclients ON T1.userid = tblclients.id
            WHERE (SELECT COUNT(*) FROM tblorders WHERE userid = T1.userid) = 1;