我有以下SQL命令:
SELECT * from products
WHERE id IN (
SELECT product_id, count(*)
FROM account_products
GROUP BY product_id
)
显然它不会检索任何数据,因为内部查询检索两列(product_id和count)。 但我也需要伯爵,因为我以后会用它来做一些数学。 如何使用count(*)来使用此IN查询?
谢谢!
答案 0 :(得分:4)
加入他们:
select products.*, t.product_count
from products
join (
SELECT product_id, count(*) as product_count
FROM account_products
GROUP BY product_id
) as t on t.product_id = products.id
答案 1 :(得分:1)
select products.*, count( account_products.product_id)
from products join account_products on
products.product_id = products.id
group by products.* (obviously all products-fields)
答案 2 :(得分:1)
或者当您的DBMS支持时,使用select子句中的子查询:
SELECT
products.*,
(SELECT count(*) FROM account_products ap WHERE ap.product_id = products.id) as "Number of Accounts"
from products
答案 3 :(得分:1)
这可能对您有用:
WITH MyAccountProducts AS
(
SELECT product_id, count(*) AS CountOfAccountProducts
FROM account_products
GROUP BY product_id
)
SELECT p.*,ap.CountOfAccountProducts
from products AS p
INNER JOIN MyAccountProducts AS ap ON p.id=ap.product_id