MySQL query WHERE statement which is a query itself?
So I'll try to clearly explain my goal first:
First, I want to query one table in my database for a list of usernames.
Second, I want to take those usernames, and query another table in the database and return only the rows in which these usernames appear in the username field.
Finally, I want to take this output (in JSON array form right now), and return it to the requesting client.
My query looks like this right now:
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
This works when the WHERE statement yields 1 result. So if I only get one returned userA, it works fine. But if I get multiple, I get a bunch of errors.
Here is the code in its entirety:
if (isset($_POST['username'])) {
$username = $_POST['username'];
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("TagDB");
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
}
while ($e = mysql_fetch_assoc($query)) {
$output[] = $e;
}
$output = json_encode($output);
print $output;
I get the following error on the query line:
*Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\w开发者_开发问答amp\www\tag\appgetfriendinfo.php on line 21*
So all I really need to know is, how would I write that query in MySQL so that I get returned an array of rows?
You don't need a subquery at all, you'll usually get better performance out of a join. Make sure you have indexes defined on tagusers.username, friendtable.userA and friendtable.userB
SELECT
tagusers.*
FROM
tagusers
INNER JOIN
friendtable
ON
tagusers.username = friendtable.userA
AND
friendtable.userB = '$username'
Use the IN
keyword.
$query = mysql_query("SELECT * FROM tagusers WHERE username IN
(SELECT userA FROM friendtable WHERE userB = '$username')");
Use either the IN
clause, or a JOIN like in this example:
$query = sprintf("SELECT tu.*
FROM TAGUSERS tu
JOIN FRIENDTABLE ft ON ft.usera = tu.username
WHERE ft.userB = '%s'",
mysql_real_escape_string($_POST['username']));
$result = mysql_query($query);
$output = json_encode($result);
精彩评论