简体   繁体   中英

mysql joining two tables vs using in condition

mysql - i have two tables as below

table1

city code, city name
1, chicago
2, miami
3, NY

table2

branch,branch name, city code, day, amt
50,a,1,jan, $10
32,b,2,feb, $30

i want to find branch and branch name where total amt in Jan was >$50 for brances in NY

i have code as below

select branch, branch name, sum(amt) from table2
where city code = (select city code from table1 where  city name = 'NY')
and day="jan"
group by branch, branch name
having sum(amt)>50
  1. is the above code correct?
  2. if i want cities NY and chicago then can i modify where clause as

where city code in (select city code from table1 where city name in ('NY','chicago')

  1. how could achieve same results by joining the both tables (single query)?
  2. what is the most efficient way to get this output

Your query #2 is correct.

The equivalent with a join is:

select table2.branch, table2.branch name, sum(table2.amt) 
from table2
join table1 on table1.citycode = table2.citycode
where table2.day="jan"
and table1.cityname in ('NY', 'Chicago')
group by branch, branch name
having sum(amt)>50

In my experience, MySQL performs much better with the join than where in (subquery) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM