MySQL UNION无法在哪里工作

时间:2016-08-02 03:46:28

标签: mysql

我想显示post_status0但不起作用的所有结果。即使post_status不是0,它也会显示结果。我在两个表中都有`post_status'。

MySQL查询

SELECT `id`, 
       `brand_category`, 
       `model_category`, 
       `titles`, 
       `images`, 
       `ads_main_pic`, 
       `post_status` 
FROM   post_ads 
WHERE  post_status = 0 
       AND `titles` LIKE '%de%' 
        OR `brand_category` LIKE '%de%' 
        OR `model_category` LIKE '%de%' 
UNION 
SELECT `id`, 
       `company` AS brand_category, 
       `keyword` AS model_category, 
       `title`   AS titles, 
       NULL      AS images, 
       NULL      AS ads_main_pic, 
       `post_status` 
FROM   job 
WHERE  post_status = 0 
       AND `title` LIKE '%de%' 
        OR `keyword` LIKE '%de%' 
        OR `company` LIKE '%de%' 

2 个答案:

答案 0 :(得分:3)

请将所有or条款放在parantheses中。像这样:

        where post_status = 0 and  (`title` like '%de%' OR `keyword` like '%de%' OR  `company` like '%de%')

答案 1 :(得分:0)

试试这个家伙:不要忘记每个标准的背景。

select `id`, `brand_category`, `model_category`, `titles`, `images`, `ads_main_pic`,`post_status` 
from post_ads 
where
post_status = 0 
and 
( `titles` like '%de%'
OR `brand_category` like '%de%'
OR  `model_category` like '%de%')
UNION
select `id`, `company` as brand_category, `keyword` as model_category, `title` as titles, NULL as images, NULL as ads_main_pic, `post_status` 
from job 
where 
post_status = 0 
and ( `title` like '%de%' OR `keyword` like '%de%' OR  `company` like '%de%)