简体   繁体   中英

Select all items Where cat_id= x or parent_id = x (Parent id different table)

Hi as the title say i have a php code where i sucefully echo the articles in a table, the problem is in this table i just have cat_id the parent_id is referenced in other table..

"articulos" table

id | titulo | fecha_evento | descripcion | img | cat_id

"categoriablog" table

    id | parent_id 

This is the way im making my query

$query1 = "SELECT id,titulo,fecha_evento,descripcion,img FROM articulos WHERE cat_id = 1";
    $result = mysql_query($query1);

My goal is to do something like this, but "parent_id" is in other table

$query1 = "SELECT id,titulo,fecha_evento,descripcion,img FROM articulos WHERE cat_id = 1 OR parent_id = 1";
        $result = mysql_query($query1);

JOIN the two tables:

SELECT 
  a.id, a.titulo, a.fecha_evento, a.descripcion, a.img 
FROM Article AS a 
INNER JOIN Category AS c ON a.cat_id = c.id
WHERE a.cat_id = x
   OR c.parent_id = x

You can use a sub query

SELECT id,titulo,fecha_evento,descripcion,img FROM Article
 WHERE cat_id = 1 OR cat_id IN
 (SELECT id from Category where parent_id=1)

Edit

Please note that this solution is a little bit slower than the JOIN solution in the answer by Mahmoud.

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