简体   繁体   中英

php display data from mysql database and group by

noob here, sorry if my question is not clear, but here it goes.

I have a mysql database with 2 tables (accounts and staff) I want to display the "account_name" and underneath that a list of the staff's "name" who are assigned to that account.

with the code below I get the "account_name" and only the first staff's "name" assigned to that account. some of the accounts have 2 or more staff members assigned.

I get:

Target (account_name)

staff1 ("name")

WalMart ("account_name")

staff1 ("name")


I want:

Target ("account_name")

staff1 ("name") staff2 ("name")

WalMart ("account_name")

staff1 ("name") staff2 ("name") staff3 ("name")


any and all help will be greatly appreciated.

Alex

code:

$query = "SELECT staff.name, staff.drive_id, accounts.id, accounts.account_name
FROM staff
JOIN accounts
ON staff.drive_id = accounts.id
WHERE staff.drive_id = accounts.id
AND accounts.drive_date = CURDATE()
GROUP BY accounts.account_name";
$result = mysql_query($query);

while ($staff = mysql_fetch_array($result))
{

echo "<br />";
echo $staff['account_name'];
echo "<br /><br />";
echo $staff['name'];
echo "<br />";
}

Group by will reduce all results to one result per grouped field You were after order by

$query = "SELECT staff.name, staff.drive_id, accounts.id, accounts.account_name
                        FROM staff
                        JOIN accounts
                        ON staff.drive_id = accounts.id
                        WHERE staff.drive_id = accounts.id
                        AND accounts.drive_date = CURDATE()
                        ORDER BY accounts.account_name";

In your loup you can then check whether the account_name has changed comparde to the previous result, and first echo the account details, then the name.

$result = mysql_query($query);
$account = '';

while ($staff = mysql_fetch_array($result))
{
if($account == $staff['account_name'])
  {
  echo "<br />";
  echo $staff['account_name'];
  $account = $staff['account_name'];
  }
echo "<br /><br />";
echo $staff['name'];
echo "<br />";
}

You need an operator to specify how to combine the account names, such as the following:

$query = "SELECT staff.name, staff.drive_id, accounts.id,
                 GROUP_CONCAT(accounts.account_name SEPARATOR ' ')
          FROM staff
          JOIN accounts
          ON staff.drive_id = accounts.id
          WHERE staff.drive_id = accounts.id
          AND accounts.drive_date = CURDATE()
          ORDER BY accounts.account_name"

See MySql's group by functions for more details and options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM