是这样的,现在有T1,T2,T3,T4 T5 5张表,以T1为主表,多表联查数据。
本人是这样写的:
(SELECT T1.CODE, T2.NAME,T3.TYPE,T4.ACCOUNT FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T4.ID)
WHERE…ORDERBY…LIMIT… [1]
UNION
(SELECT T1.CODE, T2.NAME,T3.TYPE,T5.ACCOUNT FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T5.ID)
WHERE…ORDERBY…LIMIT… [2],和[1]是一样的
其中ACCOUNT字段由T3.TYPE得值决定到底在T4表里查还是在T5表里查
ACCOUNT的数据不是在T4中 就是在T5中。
写出来暂时没办法测试,但感觉有点不放心。所以求帮助各高手们看看这么写有没有什么问题,或有没有更加优化性能的写法。
非常感谢!
本人是这样写的:
(SELECT T1.CODE, T2.NAME,T3.TYPE,T4.ACCOUNT FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T4.ID)
WHERE…ORDERBY…LIMIT… [1]
UNION
(SELECT T1.CODE, T2.NAME,T3.TYPE,T5.ACCOUNT FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T5.ID)
WHERE…ORDERBY…LIMIT… [2],和[1]是一样的
其中ACCOUNT字段由T3.TYPE得值决定到底在T4表里查还是在T5表里查
ACCOUNT的数据不是在T4中 就是在T5中。
写出来暂时没办法测试,但感觉有点不放心。所以求帮助各高手们看看这么写有没有什么问题,或有没有更加优化性能的写法。
非常感谢!
解决方案
28
(SELECT T1.CODE, T2.NAME,T3.TYPE,
case T3.TYPE when ‘T4值’ then T4.ACCOUNT else T5.ACCOUNT end as ACCOUNT
FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T4.ID
INNER JOIN T5 ON T1.ID=T5.ID)
WHERE…ORDERBY…LIMIT…
case T3.TYPE when ‘T4值’ then T4.ACCOUNT else T5.ACCOUNT end as ACCOUNT
FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
INNER JOIN T4 ON T1.ID=T4.ID
INNER JOIN T5 ON T1.ID=T5.ID)
WHERE…ORDERBY…LIMIT…
26
试试这个:
SELECT T1.CODE, T2.NAME,T3.TYPE,ifnull(T4.ACCOUNT,T5.account) as account FROM T1 INNER JOIN T2 ON T1.ID=T2.ID INNER JOIN T3 ON T1.ID=T3.ID left JOIN T4 ON T1.ID=T4.ID and T3.type = xxx left JOIN T5 ON T1.ID=T5.ID and T3.type = yyy WHERE...ORDERBY...LIMIT..
26
SELECT T1.CODE, T2.NAME,T3.TYPE,
case T3.TYPE
when 1 then (select ACCOUNT from T4 where id=t1.id)
when 2 then (select ACCOUNT from T5 where id=t1.id)
END
FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
WHERE…ORDERBY…LIMIT…
case T3.TYPE
when 1 then (select ACCOUNT from T4 where id=t1.id)
when 2 then (select ACCOUNT from T5 where id=t1.id)
END
FROM T1
INNER JOIN T2 ON T1.ID=T2.ID
INNER JOIN T3 ON T1.ID=T3.ID
WHERE…ORDERBY…LIMIT…