假设我有一张包含threadid
和itemid
的表格。 itemid
可以有多个条目具有相同的threadid
值...
查询:
SELECT DISTINCT
THREADID,
ITEMID
FROM THREADS
WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 10151)
的产率:
THREADID ITEMID
----------- --------------------
149 10000
149 10076
149 10123
149 10151
149 10225
149 10227
149 10243
149 10245
149 10282
149 10310
149 10311
149 10312
149 10350
2000 10151
2000 10243
如何将其包含在另一个查询中,并按查询顺序获取:
THREADID ITEMID
------------- ----------
149 13
2000 2
答案 0 :(得分:1)
你可以尝试
SELECT sub.THREADID,
COUNT(1) TOTAL
FROM (
SELECT DISTINCT
t.THREADID,
t.ITEMID
FROM THREADS t INNER JOIN
THREADS tt ON t.THREADID = tt.THREADID
AND tt.ITEMID = 10151
) sub
GROUP BY sub.THREADID
ORDER BY sub.THREADID
答案 1 :(得分:1)
WITH threads_cte AS (
SELECT DISTINCT x.threadid
FROM THREADS x
WHERE x.itemid = ?)
SELECT t.threadid,
COUNT(DISTINCT t.itemid) 'num_itemid'
FROM THREADS t
JOIN threads_cte tc ON tc.threadid = t.threadid
GROUP BY t.threadid
SELECT t.threadid,
COUNT(DISTINCT t.itemid) 'num_itemid'
FROM THREADS t
JOIN (SELECT DISTINCT x.threadid
FROM THREADS x
WHERE x.itemid = ?) y ON y.threadid = t.threadid
GROUP BY t.threadid
答案 2 :(得分:0)
with FirstQuery AS
(
SELECT DISTINCT THREADID, ITEMID FROM THREADS WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 10151)
)
SELECT THREADID, COUNT(*)
FROM FirstQuery;
答案 3 :(得分:0)
SELECT DISTINCT THREADID, COUNT(ITEMID) AS ITEMS
FROM THREADS
WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 1059)
GROUP BY THREADID
ORDER BY THREADID