在INNER JOINS中使用SQL变量

时间:2013-01-16 15:47:58

标签: mysql sql

我试图使用一个变量来计算我对特定id的行数,如果我在没有内部联接的情况下使用它,它可以很好地工作,否则不行,这里是没有连接的部分

    select
                            cd.basis_point bpt,
                            cd.created,
                            @version:=@version+1 version
                        from tbl_class_det cd, (select @version:=1) v
                        where (cd.class_uuid='{$row['uuid']}')
                        and (cd.created>(
                                                        select
                                                            created
                                                        from tbl_class_det
                                                        where (class_uuid=cd.class_uuid)
                                                        order by created asc
                                                        limit 1
                                                    ))
                        order by cd.created asc

带有连接的部分会出错:

    select c.name,
                            fd.value bpt,
                            fd.created,
                            @version:=@version+1 version
                        from tbl_fee_det fd, (select @version:=1) v
                            INNER JOIN tbl_fee f ON f.uuid = fd.fee_uuid
                            INNER JOIN tbl_class c ON c.uuid = f.class_uuid
                        where (fd.created>(
                                                        select
                                                            created
                                                        from tbl_class_det
                                                        where (fee_uuid=f.uuid)
                                                        order by created asc
                                                        limit 1
                                                    ))
                        order by fd.created asc;

1 个答案:

答案 0 :(得分:1)

您正在使用显式和隐式连接的组合。您不应该将JOIN语法与逗号语法混合使用。如果您需要,请使用与此类似的子查询:

select name,
    value bpt,
    created,
    @version:=@version+1 version
from
(
    select c.name,
        fd.value,
        fd.created,
        f.uuid
    FROM tbl_fee_det fd
    INNER JOIN tbl_fee f 
        ON f.uuid = fd.fee_uuid
    INNER JOIN tbl_class c 
        ON c.uuid = f.class_uuid
) f, (select @version:=1) v
where (created>(select created
                   from tbl_class_det
                   where (fee_uuid=f.uuid)
                   order by created asc
                   limit 1))
order by created asc;