如果存在其他行,如何跳过行

时间:2014-02-12 16:23:36

标签: mysql tsql

我正在尝试提供一个简单的SQL语句,以帮助输出用户需要的内容:

  SELECT 
    tbl, bundleID, productID, quantity, cardValue, a.title, orderLineGUID
  FROM
  (
    SELECT 'OLNOVPS' tbl, ol.orderLineGUID, ol.bundleID, 
           ol.productID, ol.quantity, ol.cardValue, m.title 
      from orderLinesNoVPS ol 
      inner JOIN productMeta m ON ol.productID = m.productID
      where ol.orderID = 31687478 

    UNION ALL

    SELECT 'OL' tbl, ol.orderLineGUID, ol.bundleID, 
            ol.productID, ol.quantity, ol.cardValue, m.title 
      from orderLines ol 
      inner JOIN productMeta m ON ol.productID = m.productID
      where ol.orderID = 31687478 
  ) a
  WHERE 
    a.productID > 100000;

结果是:

enter image description here

我想要完成的内容仅显示前两行,因为OLNOVPS中的OL占先例...

换句话说,如果存在OLNOVPS + orderLineGUID,则不应显示OL,如果不存在,则应显示OL因为没有OLNOVPS先例

任何人都可以帮我一把......我有点卡在这一部分。

2 个答案:

答案 0 :(得分:0)

这有点难看,但它会起作用......

您可以使用

IF (exists(SELECT 'OLNOVPS' tbl, ol.orderLineGUID, ol.bundleID, 
       ol.productID, ol.quantity, ol.cardValue, m.title 
  from orderLinesNoVPS ol 
  inner JOIN productMeta m ON ol.productID = m.productID
  where ol.orderID = 31687478 ))
BEGIN
  SELECT 'OLNOVPS' tbl, ol.orderLineGUID, ol.bundleID, 
       ol.productID, ol.quantity, ol.cardValue, m.title 
  from orderLinesNoVPS ol 
  inner JOIN productMeta m ON ol.productID = m.productID
  where ol.orderID = 31687478 
END
ELSE
    SELECT 'OL' tbl, ol.orderLineGUID, ol.bundleID, 
        ol.productID, ol.quantity, ol.cardValue, m.title 
  from orderLines ol 
  inner JOIN productMeta m ON ol.productID = m.productID
  where ol.orderID = 31687478 
END

答案 1 :(得分:0)

这样的事可能有用吗? (难看)

  SELECT 
    case when min(tbl) = 1 then 'OLNOVPS' else 'OL' end as tbl, bundleID, productID, quantity, cardValue, a.title, orderLineGUID
  FROM
  (
    SELECT 1 tbl, ol.orderLineGUID, ol.bundleID, 
           ol.productID, ol.quantity, ol.cardValue, m.title 
      from orderLinesNoVPS ol 
      inner JOIN productMeta m ON ol.productID = m.productID
      where ol.orderID = 31687478 

    UNION ALL

    SELECT 2 tbl, ol.orderLineGUID, ol.bundleID, 
            ol.productID, ol.quantity, ol.cardValue, m.title 
      from orderLines ol 
      inner JOIN productMeta m ON ol.productID = m.productID
      where ol.orderID = 31687478 
  ) a
  WHERE 
    a.productID > 100000
  GROUP BY
    bundleID, productID, quantity, cardValue, a.title, orderLineGUID