Reputation: 10340
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?
Upvotes: 0
Views: 78
Reputation: 51
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 ++;
}
Upvotes: 1
Reputation: 166
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...
Upvotes: 1
Reputation: 1269653
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.
Upvotes: 2
Reputation: 516
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
Upvotes: 1