Wordpress自定义查询两个表以获取分层数据

时间:2012-06-25 19:02:10

标签: php mysql wordpress wpdb

使用Wordpress并使用其功能在两个自定义表上查询数据库。我试图以“树/分组”格式输出数据。例如:

Team Name One
- Player Name One
- Player Name Two
- Player Name Three
- Etc...

Team Name Two
- Player Name one
- Player Name Two
- Player Name Three
- Etc...

我不确定以这种方式显示结果需要什么。这是我加入表格的一个查询...

global $wpdb;
$user_id = '1';
$teamlist = $wpdb->get_results( $wpdb->prepare( 
"
SELECT
fv_teams.team_id AS team_teamid,
fv_players.player_id,
fv_teams.team_name AS teamname,
fv_players.player_fname AS fname,
fv_players.player_lname AS lname,
fv_players.player_team AS team,
fv_players.player_position AS position
FROM
fv_teams
INNER JOIN fv_players ON fv_teams.team_id = fv_players.team_id
WHERE
fv_teams.user_id = %d
",
$user_id
), OBJECT );

我当然可以得到以下结果...

foreach ( $teamlist as $teamrow ) 
{
echo 'Team: ' .  $teamrow->teamname . '<br />';
echo 'Player ID: ' .  $teamrow->fname . '<br />';
}

但是团队名称将在结果中重复为

Team Name One
- Player One
Team Name One
- Player Two
Team Name One
- Player Three
- Etc...

我很确定我需要在那里添加一个嵌套循环,但我不确定所需的编码。

任何想法或方向都会对一个刚刚失去了大部分头发的人非常有帮助。 ; )

2 个答案:

答案 0 :(得分:3)

礼仪上不确定回答你自己的问题,但我能够根据在循环中嵌套第二个查询得到我需要的东西。

$teamlist = $wpdb->get_results( $wpdb->prepare( 
"SELECT *
 FROM fv_teams
 WHERE user_id = '1'
",
$user_id
), OBJECT );


foreach ( $teamlist as $teamrow ) 
{
$get_team_id = $teamrow->team_id;
echo  '<hr>';
echo '<h2>' . $teamrow->team_name . '</h2>';
$playerlist = $wpdb->get_results( $wpdb->prepare( 
    "SELECT *
     FROM fv_players 
     WHERE team_id = %d
    ",
    $get_team_id
), OBJECT );


    echo '<ul>';
    foreach ( $playerlist as $playerrow ) 
    {
        echo '<li>Player Name: ' .  $playerrow->player_fname . '</li>';
    }
    echo '</ul>';   
}

它需要清理,但对我有用。

答案 1 :(得分:0)

你需要在teamid上使用Group by

示例:http://www.techonthenet.com/sql/group_by.php

编辑您需要编写两个循环。

<?php 
 // in plain language
 if(TeamName has another value)
  display name;
   if (playername has another value)
    display playername;
   end if
 end if
 ?>