选择慢选择

时间:2013-05-20 09:51:09

标签: mysql sql

我目前在select中使用select来检查表中是否存在数据:

select
    a.id,
    a.desc,
    a.serial,
    a.partno,
    a.maintact,
    a.lcnalc,
    a.datedue,
    a.intrem,
    a.lifetype,
    (select b.id from assets b where
        (b.maintact = a.maintact) and
        (b.aircraft_id = a.aircraft_id) and
        (b.inittype = "STRT") and
        (b.initlcnalc = a.lcnalc OR b.initlcnalc = "")) as parent
    from assets a where aircraft_id = 6;

我想知道的是一种更有效的方法来进行上述查询?

2 个答案:

答案 0 :(得分:2)

尝试使用JOIN会更快:

select
    a.id,
    a.desc,
    a.serial,
    a.partno,
    a.maintact,
    a.lcnalc,
    a.datedue,
    a.intrem,
    a.lifetype,
    b.id
from assets a 
join assets b
    ON (b.maintact = a.maintact) and
    (b.aircraft_id = a.aircraft_id) and
    (b.inittype = "STRT") and
    (b.initlcnalc = a.lcnalc OR b.initlcnalc = "")
where a.aircraft_id = 6;

答案 1 :(得分:0)

您需要使用left join执行此操作,以确保从assets获取所有行。以下是您想要的:

select
    a.id,
    a.desc,
    a.serial,
    a.partno,
    a.maintact,
    a.lcnalc,
    a.datedue,
    a.intrem,
    a.lifetype,
    b.parent
from assets a left outer join
     (select maintact, aircraft_id, lcnalc, id
      from assets a
      group by maintact, aircraft_id, lcnal
     ) b
     on b.maintact = a.maintact) and
        (b.aircraft_id = a.aircraft_id) and
        (b.inittype = 'STRT') and
        (b.initlcnalc = a.lcnalc)
where a.aircraft_id = 6;

警告是表达式b.initlcnalc = a.lcnalc OR b.initlcnalc = ""。我不确定应该做什么。可能会在输出中引入重复的行。您可能需要第二次连接来处理这种情况。