如何从两个不同的表中获取两个不同的列值,一个值表依赖于其他表值

时间:2012-10-15 13:04:12

标签: mysql

以下查询是我之前使用过的...但我想将这两个查询结合起来以提高性能

select a, b, c
  from table1
 where d LIKE 'xxx'
   and f like 'yyyy'
 order by b desc;

我正在执行上述查询并阅读值。

对于上面的每个b值,再次在循环中执行以下查询。

select count(*) 
  from table2 where b=? AND js_email_id IN 
(
  select js_email_id 
    from js_initialsignup 
   where UCase(jsaccountstatus) LIKE UCase('live') 
     AND UCase(js_status) LIKEUCase('accepted')
)

如何组合两个查询并一次获取计数和值?

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT t1.a, t1.b, t1.c, COUNT(t2.*) 
FROM table1 t1
INNER JOIN table2 t2 ON t1.b = t2.b
INNER JOIN js_initialsignup j ON t2.js_email_id  = j.js_email_id 
WHERE t1.d LIKE 'xxx' 
  AND t1.f like 'yyyy'
  AND UCase(j.jsaccountstatus) LIKE UCase('live') 
  AND UCase(j.js_status) LIKE UCase('accepted'))" 
GROUP BY t1.a, t1.b, t1.c
ORDER BY by t1.b DESC;

答案 1 :(得分:0)

select a,b,c,
       (select count(*) 
from table2 where b=a.b AND js_email_id IN 
(
  select js_email_id 
  from js_initialsignup 
  where UCase(jsaccountstatus) LIKE UCase('live') 
    AND UCase(js_status) LIKEUCase('accepted')
)) as cnt

from table1 a