带有 JOIN SQL 的 WHERE 子句
WHERE clause with JOIN SQL
SELECT AVG(score) AS avg_score, st.name
FROM firstTable AS ft
LEFT JOIN secondTable AS st
ON ft.dog_id = st.dog_id
WHERE (SELECT COUNT(ft.dog_id) FROM firstTable) > 1
GROUP BY dog_id
where 子句似乎没有做任何事情。这是为什么? - 我实际上是在尝试仅将平均分数输出给在第一个 table
中出现不止一次的狗
您应该使用 INNER
联接,因为您只需要在两个表中都匹配的狗并在 HAVING
子句中添加条件:
SELECT AVG(ft.score) AS avg_score, st.name
FROM secondTable AS st INNER JOIN firstTable AS ft
ON ft.dog_id = st.dog_id
GROUP BY st.dog_id
HAVING COUNT(*) > 1;
SELECT AVG(score) AS avg_score, st.name
FROM firstTable AS ft
LEFT JOIN secondTable AS st
ON ft.dog_id = st.dog_id
WHERE (SELECT COUNT(ft.dog_id) FROM firstTable) > 1
GROUP BY dog_id
where 子句似乎没有做任何事情。这是为什么? - 我实际上是在尝试仅将平均分数输出给在第一个 table
中出现不止一次的狗您应该使用 INNER
联接,因为您只需要在两个表中都匹配的狗并在 HAVING
子句中添加条件:
SELECT AVG(ft.score) AS avg_score, st.name
FROM secondTable AS st INNER JOIN firstTable AS ft
ON ft.dog_id = st.dog_id
GROUP BY st.dog_id
HAVING COUNT(*) > 1;