[英]nested inner join with select query in mysql
大家好,有人可以告訴我這是什么最好的方法嗎?我的意思是,與之相比,這行代碼更少的任何其他方法,讓我先顯示查詢
select agent.*, count(que.id) queue_count
from table agent
left join (select * from table2 q
INNER JOIN table3 p on q.path_id=p.id
where q.status=1 p.name='demo') que
on que.agent_id=agent.id
left join table3 path on path.id=que.path_id
group by agent.id
order by queue_count
我現在有3個表,我想聯接所有表並再次選擇內部聯接2聯接表,即帶有where子句的表2和3
要獲取有關代理的所有信息,然后左鍵連接以從另一個表中獲取計數,通常需要按所有非聚合字段進行分組...如果您的代理表具有一堆字段,那會更好預先匯總您的子查詢,以便僅獲取基於每個agentId的計數...那么您每個代理至少要有一條記錄,並且可以對該代理進行簡單的LEFT-JOIN操作。
我假設您對“表”,“表2”,“表3”的表引用實際上是實際表的假名稱,但是在查詢中分別使用了“代理”,“ p”和“ q”的別名。
select
agent.*,
que.AgentQueueCount queue_count
from
table agent
left join
(select
q.agent_id,
count(*) AgentQueueCount
from
table2 q
INNER JOIN table3 p
on q.path_id = p.id
AND p.name='demo'
where
q.status = 1
group by
q.agent_id ) que
on agent.id = que.agent_id
order by
que.AgentQueueCount
在此,子查詢已經在匹配的路徑ID和路徑名稱上進行內部聯接。
刪除表關鍵字,並在條件中添加AND。
select agent.id, count(que.id) queue_count
from agent
left join (select * from table2 q
INNER JOIN table3 p on q.path_id=p.id
where q.status=1 AND p.name='demo') que
on que.agent_id=agent.id
left join table3 path on path.id=que.path_id
group by agent.id
order by queue_count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.