简体   繁体   中英

How to create one query instead of two separated queries?

I have two queries like this:

$stm = $db->prepare(" SELECT * from table1 where word = :word ");
$stm->bindValue(':word', $word, PDO::PARAM_STR);
$stm->execute();

$iterator = 0;
while ($end = $stm->fetch()) {

    foreach ($db-query(" SELECT * from table2 where id = $end['id']") as $row) {
        echo $row['title'];
    }

    $iterator ++;
}

Now I want to know, is it possible to I write a sub-query instead of that separated query? In other word how can I write those two queries in one query?

The answer to your question is that you can do this in the database. And you should.

A typical response is that you should learn join . However, in this case, in or exists is more appropriate:

select t2.*
from table2 t2
where t2.id in (select id from table1 where word = :word);

I do find it surprising that the condition connecting the two tables is on a column called id in both tables.

You can use join for this take a look at this query

    SELECT table1.id, table2.title
    FROM table1
    INNER JOIN table2
    ON table1.id=table2.id;
    WHERE word = :word

You can learn more about joins from here

Is JOIN your solution?

SELECT main.*, joinedTable.* FROM T1 as main
LEFT JOIN T2 as joinedTable
ON main.id=joinedTable.id
WHERE main.word = :word

I Didn't try this out...

Sure, you can use INNER JOIN

$stm = $db->prepare(" SELECT t2.* from 
                       table1 t1  INNER JOIN table2 t2 ON (t2.id = t1.id) 
                       WHERE t1.word = :word "); 
$stm->bindValue(':word', $word, PDO::PARAM_STR);
$stm->execute();

$iterator = 0;
while ($row = $stm->fetch()) {
   echo $row['title'];
   $iterator ++;
}

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