简体   繁体   English

字段列表中的SQL WHERE子查询

[英]SQL WHERE Subquery in Field List

I have query like: 我有这样的查询:

SELECT field
FROM table
WHERE
    (
        SELECT COUNT(*)
        FROM table2
        WHERE table2.field = table.field
    )
    !=
    (
        SELECT COUNT(*)
        FROM table3
        WHERE table3.field = table.field
    )

Now I want to have those WHERE subqueries in my field list like: 现在,我想在字段列表中添加以下WHERE子查询:

SELECT field, count1, count2
FROM table
WHERE
    (
        SELECT COUNT(*)
        FROM table2
        WHERE table2.field = table.field
    ) AS Count1
    !=
    (
        SELECT COUNT(*)
        FROM table3
        WHERE table3.field = table.field
    ) AS Count2

Is this possible? 这可能吗? Of course I could put those subqueries in the field list, but then I can't compare them. 当然,我可以将这些子查询放在字段列表中,但是之后我无法对其进行比较。

Any ideas? 有任何想法吗?

You can do this if you use Sql Server : 如果使用Sql Server则可以执行以下操作:

SELECT field, ca2.c2, ca3.c3
FROM table t
cross apply(SELECT COUNT(*) c2
            FROM table2 t2
            WHERE t2.field = t.field)ca2
cross apply(SELECT COUNT(*) c3
            FROM table3 t3
            WHERE t3.field = t.field)ca3
where ca2.c2 <> ca1.c1

Use correlated sub-selects to count. 使用相关的子选择进行计数。 Wrap up in a derived table: 在派生表中总结:

select dt.* from
(
SELECT field,
       (SELECT COUNT(*)
        FROM table2
        WHERE table2.field = table.field) as cnt1,
       (SELECT COUNT(*)
        FROM table3
        WHERE table3.field = table.field) as cnt2
FROM table
) dt
where dt.cnt1 <> dt.cnt2

You just need to use a Derived Table: 您只需要使用派生表:

select *
from
 (
   SELECT field, 
    (
        SELECT COUNT(*)
        FROM table2
        WHERE table2.field = table.field
    ) AS Count1,
    (
        SELECT COUNT(*)
        FROM table3
        WHERE table3.field = table.field
    ) AS Count2
   FROM table
 ) dt
WHERE Count1 <> Count2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM