Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn these multiple mysql_querys into 1 query?

Tags:

sql

join

php

mysql

I have two tables: users and threads. When a thread is created, it will store the user_id in the table as author_id. I want to display the thread name and the username of its author with the same query. I am currently using two querys as shown:

$query2 = mysql_query("SELECT author_id FROM threads WHERE id = $threadId") or die(mysql_error());
$result2 = mysql_fetch_array($query2);
$author_id = $result2['author_id'];
$query3 = mysql_query("SELECT username FROM users WHERE id = $author_id") or die(mysql_error());
$result3 = mysql_fetch_array($query3);
$author_name = $result3['username'];
like image 312
Tom Oborne Avatar asked Jan 17 '26 20:01

Tom Oborne


2 Answers

<?php
$sql = '
    SELECT t.name, u.username
    FROM threads t
    JOIN users u ON t.author_id = u.id
    WHERE t.id = ' . (int)$threadId . '
';
list($thread_name, $author_name) = mysql_fetch_row(mysql_query($sql));

P.S. Mysql php extension is deprecated.

like image 116
userlond Avatar answered Jan 20 '26 11:01

userlond


Try this query:

SELECT username 
FROM users 
WHERE id = (SELECT author_id 
            FROM threads 
            WHERE id = $threadId 
            LIMIT 1)

Note: Limit 1 is not mandatory as id is unique.

like image 45
louk Avatar answered Jan 20 '26 11:01

louk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!