简体   繁体   中英

Select value in mysql but check another database at clause WHERE

I'm trying to select values from a database, but I need to check another value in another database .

I created this code, but only get 1 result and I don't know why:

SELECT `id` FROM `mc_region` 
    WHERE `is_subregion` = 'false' 
        AND lastseen < CURDATE() - INTERVAL 20 DAY 
        AND (SELECT id_region FROM mc_region_flags 
                    WHERE flag <> 'expire' 
                    AND id_region = mc_region.id
            ) 
LIMIT 0, 30

What I've made wrong?

@Edit
I think I know why this code is not working. At database mc_region_flags not all records from the primary database has flag.

I would like to do the following:

1º Select all records on the first database, where is not subregion and lastseen is more than 20 day
2º Check if any result on the 1st database has flag 'expire', if yes, they are not included in the result.

I cant do this in 1 only SQL Code?

@Edit2

I created this code that simulate FULL JOIN but seems that WHERE is not work

SELECT *
    FROM mc_region AS r RIGHT OUTER JOIN
         mc_region_flags AS f ON r.id = f.id_region
UNION ALL
    SELECT * from 
        mc_region AS r LEFT OUTER JOIN 
        mc_region_flags AS f
        ON r.id = f.id_region
WHERE r.is_subregion = 'false' 
AND f.flag = 'exipre' 
AND r.lastseen < CURDATE() - INTERVAL 20 DAY

Problems WHERE not work

  1. f.flag is not 'expire'
  2. f.lastseen is not > 20 days

结果

在内部嵌套之前,选择add:id in(选择...)

UPDATED

SELECT * 
  FROM `mc_region` AS r LEFT JOIN 
       `mc_region_flags` AS f ON r.`id` = f.`id_region`
 WHERE r.`is_subregion` = 'false' AND 
       r.`lastseen` < CURDATE() - INTERVAL 20 DAY AND
       COALESCE(f.`flag`, '-') <> 'expire'
LIMIT 0, 30;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM