用于连接2个表的SQL查询

时间:2013-10-09 02:41:32

标签: mysql sql sql-server postgresql join

我想在postgres中加入以下两个表:

table1 (
   i1 character varying
 , i2 character varying
 , i3 character varying
)  

table2 (
   i4 character varying
 , startorend character varying
 , begin integer
 , end character integer
)

table1包含以下值:

  p1  p2    p3
  p4  p10   p6
  p7  p8    p9
  p99 p199  p299

table2包含以下值:

  p4  begin 1   12
  p4  end   13  14
  p7  begin 19  20
  p1  end   21  22

现在我想加入2个表,以便遵守下面提到的规则:

1. When table1.i1=table2.i4, then 
   1a. If there are 2 rows containing begin and end corresponding to table2,
       then choose table2.begin and table2.end
       from the begin and end columns respectively from table2.i4.  
   1b. If there is only 1 row containing begin or end corresponding to table2,
       then assume and write the default value as end(9999) and begin(0).

通过应用上述规则,我得到下面提到的表格:

p4      1            14
p1      0(default)   22 (as it just contains end column in table 2, therefore 0(begin) as default is inserted)
p7      19           9999(default) (as it just contains begin column in table2, therefore 9999(end) as default is inserted)

我可以有效地加入表格,但我们可以随时插入默认值吗?

2 个答案:

答案 0 :(得分:1)

您应该可以通过为begin和end值创建嵌套选择,执行外连接,然后在找不到匹配的行时使用ISNULL替换默认值来实现。

SELECT Table1.i1, 
       ISNULL(BeginValues.begin, 0), 
       ISNULL(EndValues.end, 9999)
FROM Table1 LEFT OUTER JOIN 
        (SELECT i4, begin 
         FROM Table2 
         WHERE Table2.startorend = 'begin') AS BeginValues 
        ON Table1.i1 = BeginValues.i4 LEFT OUTER JOIN 
        (SELECT i4, end 
         FROM Table2 
         WHERE Table2.startorend = 'end') AS EndValues 
        ON Table1.i1 = EndValues.i4

答案 1 :(得分:1)

SELECT i4
      ,CASE WHEN count(*) > 1 OR min(startorend) = 'begin' THEN min("begin")
            ELSE 0 END AS the_begin
      ,CASE WHEN count(*) > 1 OR min(startorend) = 'end'   THEN min("end")
            ELSE 9999 END AS the_end
FROM   table2 t2
WHERE  EXISTS (SELECT 1 FROM table1 t1 WHERE t1.i1 = t2.i4)
GROUP  BY i4

假设 table1.i1UNIQUE,或者仅存在一个或多个匹配行。

beginendreserved words in the SQL standard。您不应将它们用作标识符。这就是我引用双引号的原因。