I have two tables:
Table alpha
id | title | catid
1 | winter | 105
2 | summer | 105
3 | fall | 20
4 | spring | 12
Table beta
id | author
1 | john
2 | mike
3 | bill
Table result — I would like to generate the following table by matching the id from the two tables above. Using only those colums WHERE "catdid" is 105.
id | author | title
1 | john | winter
2 | mike | summer
I have the following query:
$table_alpha = "alpha";
$table_beta = "beta";
$sql = "
SELECT id, title, catid, author
FROM $table_alpha, $table_beta
WHERE catid = 105
…
???
…
";
Any ideas? Thanks.
I'm writing this on my phone, so I hope it works, but you really just need to use a JOIN
.
$table_alpha = "alpha";
$table_beta = "beta";
$sql = "
SELECT id, title, catid, author
FROM $table_alpha
JOIN $table_beta USING(id)
WHERE catid = 105
";
The USING
clause tells the query to treat id
the thing to join on. That should make it safe to query for it by name without stating which id
to retrieve (man I wish I could verify that, but no SQL on my phone :-p)
This should do the job:
SELECT a.id, b.author, a.title
FROM alpha AS a
INNER JOIN beta AS b
ON a.id = b.id
WHERE a.catid = 105;
Your query was quite close, you need to use a JOIN with a condition:
$table_alpha = "alpha";
$table_beta = "beta";
$sql = "
SELECT $table_alpha.id, title, author
FROM $table_alpha
JOIN $table_beta
ON $table_alpha.id=$table_beta.id
WHERE catid = 105
"