日期:2014-05-18  浏览次数:20739 次

SQL两表查询写法改进
现在又有t1,t2两张表
t1 有a1,a2,a3(pk:a1,a2)
t2 有b1,b2,b3(pk:b1,b2)
现在要查询条件是
a1=b1 and a2>=b2 and b2 是最大的数据
最后取得字段a1,a2,b2,b3,我有2个问题
问题1 这样的代码对吗?
SELECT a1,a2,b2,b3
FROM (SELECT a1,a2, MAX(b2) AS mb2
  FROMt1,t2
  WHERE a1 = b1 AND a2 >= b2 
  GROUP BY a1,a2 )A,
  t2 B
WHERE A.a1 = B.a1 
AND A.mb2 = B.b2
如果对,但是我还是觉得太繁琐了
问题2 高效的写法吗?

------解决方案--------------------
语句有点区别,原因是鸟书中的最大有歧义

你的语句等同于

SQL code
SELECT A.A1,A.A2,B.B2,B.B3
FROM T1 A 
INNER JOIN T2 B
ON A.A1=B.B1
AND A.A2 >= B.B2
AND NOT EXISTS (
  SELECT 1 FROM T2
  WHERE B1 = B.B1
  AND A.A2 >= B2
  AND B2 > B.B2
  )

------解决方案--------------------
SQL code

CREATE TABLE t1
(    a1 INT,
    a2 INT,
    a3 INT
)
CREATE TABLE t2
(    b1 INT,
    b2 INT,
    b3 INT
)
INSERT INTO t1
SELECT 1,3,1 UNION
SELECT 2,3,1 UNION
SELECT 3,1,1

INSERT INTO t2
SELECT 1,2,3 UNION
SELECT 1,1,4 UNION
SELECT 3,1,1



SELECT *
FROM t1,t2
WHERE a1 = b1 AND a2 >= b2 AND b2 >= ALL(SELECT b2 FROM t2 WHERE a1 = b1 AND a2 >= b2)