我的数据库中有4个自定义表格 - wp_api_teams
,wp_api_matches
,wp_api_competitions
和wp_api_federations
。它们是我的Wordpress数据库的一部分,这就是它们的外观(我正在使用外键和所有这些):
我正在尝试输出属于联盟的所有团队。当我在phpmyadmin中运行它时,它可以工作:
SELECT
wp_api_teams.team_id,
wp_api_teams.title,
wp_api_competitions.comp_id,
wp_api_competitions.title,
wp_api_federations.federation_id,
wp_api_federations.title
FROM
wp_api_teams
JOIN wp_api_matches
ON wp_api_teams.team_id = wp_api_matches.hometeam_id OR wp_api_teams.team_id = wp_api_matches.awayteam_id
JOIN wp_api_competitions
ON wp_api_matches.comp_id = wp_api_competitions.comp_id
JOIN wp_api_federations
ON wp_api_competitions.federation_id = wp_api_federations.federation_id
WHERE wp_api_federations.federation_id = 1
GROUP BY (wp_api_teams.team_id);
我得到了我正在寻找的确切结果。
-----------------------------------------------------------------------------------
| team_id | title | comp_id | title | federation_id | title |
1 Arsenal 1 Premier League 1 England
2 Chelsea 1 Premier League 1 England
3 Liverpool 1 Premier League 1 England
4 Manchester United 1 Premier League 1 England
5 Manchester City 1 Premier League 1 England
这是我在Wordpress中使用的代码:
global $wpdb;
$sql = "
SELECT
wp_api_teams.team_id,
wp_api_teams.title,
wp_api_competitions.comp_id,
wp_api_competitions.title,
wp_api_federations.federation_id,
wp_api_federations.title
FROM
wp_api_teams
JOIN wp_api_matches
ON wp_api_teams.team_id = wp_api_matches.hometeam_id OR wp_api_teams.team_id = wp_api_matches.awayteam_id
JOIN wp_api_competitions
ON wp_api_matches.comp_id = wp_api_competitions.comp_id
JOIN wp_api_federations
ON wp_api_competitions.federation_id = wp_api_federations.federation_id
WHERE wp_api_federations.federation_id = 1
GROUP BY wp_api_teams.team_id
";
$test = $wpdb->get_results($sql);
echo('<pre>');
print_r($test);
echo('</pre>');
我得到的结果是缺少两个表格列:
Array
(
[0] => stdClass Object
(
[team_id] => 1
[title] => England
[comp_id] => 1
[federation_id] => 1
)
[1] => stdClass Object
(
[team_id] => 2
[title] => England
[comp_id] => 1
[federation_id] => 1
)
....等等。
如您所见,结果中缺少wp_api_teams.title
和wp_api_competitions.title
列。
所以我的问题是,为什么会发生这种情况,为什么这些列被省略,我可以做些什么来解决这个问题,因为我在返回的结果中绝对需要它们。相同的查询如何在WP与PHPmyadmin中产生不同的结果。
这是一个已知错误还是我的代码有问题?
我在10.2.14-MariaDB
上运行localhost
,所有表格引擎都是InnoDB
。
答案 0 :(得分:1)
您的列名在结果集中是相同的。您需要提供别名:
global $wpdb;
$sql = "
SELECT
wp_api_teams.team_id,
wp_api_teams.title as team_title,
wp_api_competitions.comp_id,
wp_api_competitions.title as competition_title,
wp_api_federations.federation_id,
wp_api_federations.title as federation_title
FROM
wp_api_teams
JOIN wp_api_matches
ON wp_api_teams.team_id = wp_api_matches.hometeam_id OR wp_api_teams.team_id = wp_api_matches.awayteam_id
JOIN wp_api_competitions
ON wp_api_matches.comp_id = wp_api_competitions.comp_id
JOIN wp_api_federations
ON wp_api_competitions.federation_id = wp_api_federations.federation_id
WHERE wp_api_federations.federation_id = 1
GROUP BY wp_api_teams.team_id
";
$test = $wpdb->get_results($sql);
echo('<pre>');
print_r($test);
echo('</pre>');