考虑这两个数据库表:
Users
UID Name
1 Shawn
2 Sean
Photos
UID Description
1 Beauty
2 Ugliness
我想要检索一个这样的数组:
Array
(
[0] => Array
(
[UID] => 1
[Description] => Ugliness
)
)
请注意,UID为1,但Description对应于Photos表的UID 2。事实上,我想要的是检索表用户的UID 1的信息,但是对于表照片的UID 2。所以从理论上讲,我会像这样编写我的SQL:
SELECT * FROM Users, Photos WHERE Users.UID = '1' AND Photos.UID = '2'
以下是我尝试获得我希望的内容:
$myArray_both = array();
$sql = "SELECT * FROM Users, Photos WHERE Users.UID = '1' AND Photos.UID = '2'";
$results = mysql_query($sql);
while($result = mysql_fetch_array($results, MYSQL_BOTH)) // MYSQL_BOTH is the default behaviour but I added it in for clarity
{
array_push($myArray_both, $result);
}
echo("<h2>Using MYSQL_BOTH</h2>");
echo("<pre>");
print_r($myArray_both);
echo("</pre>");
/* This has the following output:
Array
(
[0] => Array
(
[0] => 1
[UID] => 2
[1] => Ugliness
[Description] => Ugliness
)
)
**which is not good for me because I want to be able to access the UID with $result['UID'], but I want the UID returned to be 1, not 2.**
*/
$myArray_assoc = array();
$sql = "SELECT * FROM Users, Photos WHERE Users.UID = '1' AND Photos.UID = '2'";
$results = mysql_query($sql);
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
array_push($myArray_assoc, $result);
}
echo("<h2>Using MYSQL_ASSOC</h2>");
echo("<pre>");
print_r($myArray_assoc);
echo("</pre>");
/* This has the following output:
Array
(
[0] => Array
(
[UID] => 2
[Description] => Ugliness
)
)
**This also doesn't work because I want to obtain UID 1, not 2**
*/
$myArray_num = array();
$sql = "SELECT * FROM Users, Photos WHERE Users.UID = '1' AND Photos.UID = '2'";
$results = mysql_query($sql);
while($result = mysql_fetch_array($results, MYSQL_NUM))
{
array_push($myArray_num, $result);
}
echo("<pre>");
print_r($myArray_num);
echo("</pre>");
/* This has the following output:
Array
(
[0] => Array
(
[0] => 1
[1] => Ugliness
)
)
**This gets the correct values, but I can't access them by name..**
*/
mysql_close($liendb); // Closes the database connection
?>
原来如此!我该怎么办?
答案 0 :(得分:1)
SELECT Users.UID AS userID, Users.Name, Photos.UID AS photoID, Photos.Description WHERE [blah blah blah]
HTH