2012-10-22 58 views
1

我想使用MySQL創建以下兩個查詢的交集:相交MySQL的使用可比列

1) SELECT atn_nid, atn_select_flag, atn_image_name 
FROM city, attraction WHERE cty_nid = atn_cty_nid AND cty_nid = 5; 

2) SELECT atn_nid, s2a_image_select_flag, atn_image_name 
FROM segment, seg2atn, attraction WHERE seg_nid = s2a_seg_nid AND 
s2a_atn_nid = atn_nid and seg_nid = 68 AND 
s2a_image_select_flag = true; 

注:查詢1 atn_select_flag和s2a_image_select_flag都是布爾

由於MYSQL由於某些原因不支持INTERSECT,我不知道用什麼語法來完成這個任務。任何幫助將不勝感激。

回答

0

如果我認爲正確的是:

  • 領域命名atn_...cty_...seg_...s2a_...attractioncitysegmentseg2atn,分別屬於。
  • 字段名爲..._nid是主鍵。
  • atn_cty_nid,s2a_seg_nid等是外鍵。

那麼你的第一個查詢是相同的:

SELECT atn_nid, atn_select_flag, atn_image_name 
    FROM attraction 
WHERE aty_cty_nid = 5 
; 

和你的第二個查詢是相同的:

SELECT atn_nid, TRUE, atn_image_name 
    FROM attraction 
WHERE atn_id IN 
     (SELECT s2a_atn_nid 
      FROM seg2atn 
      WHERE s2a_seg_nid = 68 
      AND s2a_image_select_flag = TRUE 
     ) 
; 

所以它們的交集是這樣的:

SELECT atn_nid, TRUE AS atn_select_flag, atn_image_name 
    FROM attraction 
WHERE atn_cty_nid = 5 
    AND atn_nid IN 
     (SELECT s2a_atn_nid 
      FROM seg2atn 
      WHERE s2a_seg_nid = 68 
      AND s2a_image_select_flag = TRUE 
     ) 
; 

(編輯補充)他們的工會是這樣的:

SELECT atn_nid, atn_select_flag, atn_image_name 
    FROM attraction 
WHERE aty_cty_nid = 5 
UNION 
SELECT atn_nid, TRUE, atn_image_name 
    FROM attraction 
WHERE atn_id IN 
     (SELECT s2a_atn_nid 
      FROM seg2atn 
      WHERE s2a_seg_nid = 68 
      AND s2a_image_select_flag = TRUE 
     ) 
; 
+0

ruakh,如果你在交集中改變seg_nid爲s2a_seg_nid,謝謝!!不幸的是,作爲新手,我只是意識到,我需要兩個查詢的UNION保留第一個查詢中的atn_select標誌和第二個(在單個列中)結果中的s2a_image_select_flag。這可以做到嗎? – all4one

+0

@ all4one:Re:'seg_nid'與's2a_seg_nid':糟糕,你是對的。 Re:'UNION':MySQL *支持'UNION',所以是的。我會更新我的答案。 – ruakh