$rtid = arg(2);
$query = "SELECT node.nid AS nid FROM node
WHERE (node.nid IN (
SELECT tn.nid AS nid
FROM taxonomy_index AS tn
LEFT OUTER JOIN taxonomy_term_hierarchy AS th ON th.tid = tn.tid
LEFT OUTER JOIN taxonomy_term_hierarchy AS th1 ON th.parent = th1.tid
LEFT OUTER JOIN taxonomy_term_hierarchy AS th2 ON th1.parent = th2.tid
WHERE (tn.tid = :rtid) OR (th1.tid = :rtid) OR (th2.tid = :rtid)
))
AND (node.status = '1') AND (node.type IN ('product'))
ORDER BY node_created DESC
LIMIT 1 OFFSET 0";
$result = db_query($query, array(':rtid' => $rtid));
After I tried some times with the help of other users' answers, I got lost. This is the code I tried, but it gives me an error ("PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'").
$query = db_select('node', 'n')
->condition('n.type', 'product')
->condition(
db_or()
->condition('tn.tid',$rtid )
->condition('th1.tid',$rtid)
->condition('th2.tid',$rtid)
)
->fields('n', array('nid'))
->extend('PagerDefault')
->limit(1);
$query->join('taxonomy_term_hierarchy', 'th', 'th.tid = tn.tid');
$query->join('taxonomy_term_hierarchy', 'th1', 'th.parent = th1.tid');
$query->join('taxonomy_term_hierarchy', 'th2', 'th1.parent = th2.tid');
$result = $query->execute();