在此查询中将连接重写为子查询

时间:2012-12-13 08:44:36

标签: sql database db2

你们可以帮我用子查询重写这个吗

SELECT 
    S.DENUMIRE, M.DENUMIRE, AN
FROM 
    SPECIALIZARE S
JOIN 
    MATERII M ON S.CODSPEC = M.CODSPEC
ORDER BY 
    S.DENUMIRE

4 个答案:

答案 0 :(得分:1)

SELECT 
    S.DENUMIRE,
    M.DENUMIRE,
    AN
FROM SPECIALIZARE S
JOIN (
    SELECT
        DENUMIRE,
        CODSPEC
    FROM MATERII
) AS M
    ON S.CODSPEC = M.CODSPEC
ORDER BY S.DENUMIRE

答案 1 :(得分:0)

假设DENUMIRE是一个整数:

SELECT S.DENUMIRE, 1 DENUMIRE, AN
  FROM SPECIALIZARE S
 WHERE EXISTS (
               SELECT * 
                 FROM MATERII M 
                WHERE S.CODSPEC = M.CODSPEC
                      AND M.DENUMIRE = 1
              )
UNION
SELECT S.DENUMIRE, 2 DENUMIRE, AN
  FROM SPECIALIZARE S
 WHERE EXISTS (
               SELECT * 
                 FROM MATERII M 
                WHERE S.CODSPEC = M.CODSPEC
                      AND M.DENUMIRE = 2
              )
UNION
SELECT S.DENUMIRE, 3 DENUMIRE, AN
  FROM SPECIALIZARE S
 WHERE EXISTS (
               SELECT * 
                 FROM MATERII M 
                WHERE S.CODSPEC = M.CODSPEC
                      AND M.DENUMIRE = 3
              )

UNION
...

依此类推每个整数值......当然这是不可行的。

你需要加入!如果您只是出于教学原因而避免避免使用JOIN关键字:

SELECT 
    S.DENUMIRE, M.DENUMIRE, AN
FROM 
    SPECIALIZARE S, MATERII M 
WHERE
    S.CODSPEC = M.CODSPEC
ORDER BY 
    S.DENUMIRE

P.S。虽然SQL的“兼容性束缚”(一个供应商在20世纪80年代支持这个并且它成为标准等)允许同一个表中的两列具有相同的名称,但在实践中它可能不是一个好主意。另外,我假设AN来自表格SPECIALIZARE但可能是拼写错误。

答案 2 :(得分:0)

你可能能够通过工会和团队来做一些愚蠢的事情。例如:

select max(s_denumire) as s_denumire,
       max(m_denumire) as m_denumire,
       codspec
    from (
        select denumire as s_denumire, null as m_denumire, codspec 
            from specializare
        union all
        select null as s_denumire, denumire as m_denumire, codspec 
            from materii
    )
    group by codspec

codspec生成一行,因此它不像连接。但你可能会用行号来解决这个问题。我会把它当作锻炼给你,因为这显然是家庭作业。

答案 3 :(得分:0)

您是否只想要两个表中的不同行?

SELECT
    SQ.DENUMIRE, SQ.AN
FROM (
    SELECT
        DENUMIRE, AN
    FROM 
        SPECIALIZARE

    UNION

    SELECT
        DENUMIRE, AN
    FROM 
        MATERII
) SQ
ORDER BY
    SQ.DENUMIRE