如何获取具有相同id的mysql表中的所有数据

时间:2013-04-24 14:40:37

标签: php mysql

我的mySQL数据库中有类似的内容:

sql table

(用户734有很多信息:传记,姓名,电话,邮件......)

我想获得一个带有分组数据的数组(在PHP中):

array(
    [734]=>
    object {
        [155] => string "Dominique",
        [4] => int(047682037),
        [1] => string "Dominique B"
    },
    [735]=>
    object {
        [155] => string "Other",
        [4] => int(0123456789),
        [1] => string "Other B"
    }
)

不仅适用于734用户,也适用于每个用户。通过一个简单的查询,我得到了一切但不是很好的顺序。我可以在SQL中创建它,或者我可能需要在PHP中重新排列数据吗?

为每个user_id获取所有相关数据的SQL查询是什么?

我无法更改数据库结构(WP和buddressress) 我不能使用本机WP功能(因为从其他站点获取数据)

5 个答案:

答案 0 :(得分:3)

SELECT * FROM (whatever your table name is)
WHERE user_id = (whatever user id you're interested in getting data for)

答案 1 :(得分:0)

$result = mysqli_query($con, "SELECT * FROM table_name WHERE user_id = 734");

或者如果您不使用mysqli:

$result = mysql_query("SELECT * FROM table_name WHERE user_id = 734");

答案 2 :(得分:0)

如果您使用的是PDO库,则可以检查PDO :: FETCH_GROUP属性。 http://php.net/manual/en/pdostatement.fetchall.php

  

<强> fetch_style:   返回按指定列的值分组的关联数组,按位ORO PDO :: FETCH_COLUMN与PDO :: FETCH_GROUP。

答案 3 :(得分:0)

$stmt = $this->_mysqli->prepare('SELECT user_id,field_id,value FROM WHERE user_id = ?');

$stmt->bind_param('i', $user_id );
$stmt->execute();
$stmt->bind_result($user_id, $field_id, $value);

while($stmt->fetch())
{
     $data[$user_id][$field_id] = $value;
}

答案 4 :(得分:0)

使用ORDER BY的解决方案:

$users = array();
$current_user = null;
$result = $mysqli->query("SELECT user_id, field_id, value FROM `TABLE_NAME` ORDER BY user_id, field_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
    if ($current_user != $row['user_id']) {
      $current_user = $row['user_id'];
      $users[$row['user_id']] = array();
    }
    $users[$row['user_id']][$row['field_id']] = $row['value'];
}

编辑

使用GROUP BYGROUP_CONCAT还有另一种解决方案:

$users = array();
$result = $mysqli->query("SELECT user_id, GROUP_CONCAT(field_id SEPARATOR '|') as fields, GROUP_CONCAT(value SEPARATOR '|') as values FROM `TABLE_NAME` GROUP BY user_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
    $fields = explode('|', $row['fields']);
    $values = explode('|', $row['values']);

    $users[$row['user_id']] = array();
    // Problem id you have your field ids and your values in separate arrays, not sure what you want to do with them
}