Mysql在一次获取中获取列值

时间:2016-01-26 15:42:10

标签: php mysql sql mysqli

我想有一个单一的查询来获取列值而没有“while”......是否可能?我有两张这样的桌子...... 业主:

+----+-------+---------+
| id | names | surname |
+------------+---------+
| 1  | John  | Red     |
| 2  | Mark  | Green   |
| 3  | Frank | Yellow  |
| ...| ...   |...      |
+------------+---------+

动物

+----+--------+--------+
| id |idOwner | animal |
+-------------+--------+
| 1  | 1      | Cat    |
| 2  | 2      | Bird   |
| 3  | 1      | Dog    |
| ...| ...    |...     |
+-------------+--------+

现在我有了这段代码:

$query='SELECT * FROM Owners WHERE id=1';
$con=new mysqli($dbhostname, $dbusername, $dbpassword, $dbname);
$result=$con->query($query);
$arr=array();
while ($own = $result->fetch_array(MYSQLI_ASSOC)) {
    $qry='SELECT animal FROM Animals WHERE idOwner=own["id"]';
    $rslt=$con->query($qry);
    $i=1;
    while ($aml = $rslt->fetch_array(MYSQLI_ASSOC)) {
        $txt='animal'.$i;
        $own['animal'.$i]=$aml['animal'];
        $i++;
    }
    $arr[]=$own;
}
$con->close();

我希望得到相同的结果,但只有一个查询,因为现在这个过程太晚了......可能吗?

2 个答案:

答案 0 :(得分:3)

是的,您所要做的就是使用JOIN:

SELECT owners.*, animals.animal
FROM owners
LEFT JOIN animals
ON owners.id = animals.idOwner

现在,您可以在一个循环中显示所有所有者及其动物,或者使用WHERE子句将查询限制为一个所有者。例如,添加此子句:

WHERE owners.id = 1

将从您在表格中显示的内容返回2行。

OP在评论中提到他希望每个所有者一排。要为每个所有者获取一行,您必须使用子查询和GROUP_CONCAT 完全未经测试 ):

SELECT owners.*, sub-animals.animal
FROM owners
LEFT JOIN (SELECT GROUP_CONCAT(animal) AS animal
          FROM animals 
          GROUP BY animals.idOwner) AS sub-animals 
ON owners.id = animals.idOwner

答案 1 :(得分:1)

是的,您可以将JOIN用于一个查询:

SELECT o.*,a.animal FROM owners o 
INNER JOIN animals a ON a.idOwner = o.id 

如果要为获取特定用户数据添加WHERE id = 1子句,则可以将此查询用作:

SELECT o.*,a.animal FROM owners o 
INNER JOIN animals a ON a.idOwner = o.id
WHERE o.id = 1