使用PHP和MySQL并将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";
如何将这两个SELECT组合成1?
答案 0 :(得分: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";
答案 1 :(得分: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")