2011-07-11 215 views
0

使用PHP和MySQL,並有2個SELECT語句結合在一起如何將2個SELECT連接在一起?

$sql="SELECT DISTINCT t1.* 
     FROM entry AS t1 
     INNER JOIN entry_tag AS t2 ON t1.entry_id=t2.entry_id 
     INNER JOIN tag AS t3 ON t3.tag_id=t2.tag_id 
     WHERE t1.title LIKE '%$key%' OR 
     t1.content LIKE '%$key%' OR 
     t3.tag LIKE '%$key%' AND t1.status='OK' 
     ORDER BY view DESC"; 

$sql="SELECT DISTINCT t1.* 
     FROM entry AS t1 
     INNER JOIN candidate AS t2 ON t1.entry_id=t2.entry_id 
     WHERE t2.name LIKE '%$key%' AND t1.status='OK' 
     ORDER BY view DESC"; 

如何將這些2個選擇合併爲1?

回答

4

使用UNION ALL:

$sql="SELECT DISTINCT t1.* 
    FROM entry AS t1 
    INNER JOIN entry_tag AS t2 ON t1.entry_id=t2.entry_id 
    INNER JOIN tag AS t3 ON t3.tag_id=t2.tag_id 
    WHERE t1.title LIKE '%$key%' OR 
    t1.content LIKE '%$key%' OR 
    t3.tag LIKE '%$key%' AND t1.status='OK' 
    UNION ALL 
    SELECT DISTINCT t1.* 
    FROM entry AS t1 
    INNER JOIN candidate AS t2 ON t1.entry_id=t2.entry_id 
    WHERE t2.name LIKE '%$key%' AND t1.status='OK' 
    ORDER BY view DESC"; 
+0

我可以使用UNION ALL多次在同一語句? –

+1

是的,你可以。但是您必須爲每個選擇提供相同的列。另外,如果要在查詢結尾處排除重複項,請使用UNION而不是UNION ALL。 – CristiC

+0

這就是我想要的 - '排除重複'。再次感謝Parkyprg。 :) –

1
select * from 
(SELECT DISTINCT t1.* 
    FROM entry AS t1 
    INNER JOIN entry_tag AS t2 ON t1.entry_id=t2.entry_id 
    INNER JOIN tag AS t3 ON t3.tag_id=t2.tag_id 
    WHERE t1.title LIKE '%$key%' OR 
    t1.content LIKE '%$key%' OR 
    t3.tag LIKE '%$key%' AND t1.status='OK' 
    ORDER BY view DESC") 
union all 
("SELECT DISTINCT t1.* 
    FROM entry AS t1 
    INNER JOIN candidate AS t2 ON t1.entry_id=t2.entry_id 
    WHERE t2.name LIKE '%$key%' AND t1.status='OK' 
    ORDER BY view DESC") 
+0

哪一個是最好的「(」,「)」之間沒有一個像Parkyprg的答案? –

+0

http://dev.mysql.com/doc/refman/5.0/en/union.html – dpp

+0

@AJ - 無論哪種方式都行。我只是更喜歡括號,所以如果我將添加一個排序表達式後,查詢結合'select ...(select ..)union all(select ...)order by ...',我可以這樣做。 – dpp