计算具有子查询的两个 table 的并集
Count union of two table that has subquery
我有这个工作查询。它有子查询计数。
SELECT
COUNT(*) AS total
FROM
(SELECT
COUNT(aset)
FROM
`public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
GROUP BY aset) t
现在我需要合并不同的 table 并从两个 table 中获取总数。此代码可以获取计数记录,但值不正确。
SELECT
COUNT(*) AS total
FROM
(SELECT
COUNT(aset)
FROM
`public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
UNION
SELECT
COUNT(aset)
FROM
`public_2`
WHERE `public_2`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
GROUP BY aset) z
请帮助我正确查询。提前致谢
使用 SELECT COUNT(DISTINCT aset)
计算您的计数,然后将它们相加。
SELECT t1.total + t2.total AS total
FROM (
SELECT COUNT(DISTINCT aset) AS total
FROM `public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8) AS t1
CROSS JOIN (
SELECT COUNT(DISTINCT aset) AS total
FROM `public_2`
WHERE `public_2`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8) AS t2
我有这个工作查询。它有子查询计数。
SELECT
COUNT(*) AS total
FROM
(SELECT
COUNT(aset)
FROM
`public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
GROUP BY aset) t
现在我需要合并不同的 table 并从两个 table 中获取总数。此代码可以获取计数记录,但值不正确。
SELECT
COUNT(*) AS total
FROM
(SELECT
COUNT(aset)
FROM
`public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
UNION
SELECT
COUNT(aset)
FROM
`public_2`
WHERE `public_2`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8
GROUP BY aset) z
请帮助我正确查询。提前致谢
使用 SELECT COUNT(DISTINCT aset)
计算您的计数,然后将它们相加。
SELECT t1.total + t2.total AS total
FROM (
SELECT COUNT(DISTINCT aset) AS total
FROM `public_1`
WHERE `public_1`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8) AS t1
CROSS JOIN (
SELECT COUNT(DISTINCT aset) AS total
FROM `public_2`
WHERE `public_2`.`aset` NOT IN
(SELECT
asset_code
FROM
application_detail
WHERE application_id = 6)
AND org_id = 7
AND status_id = 8) AS t2