【发布时间】:2015-11-27 13:45:52
【问题描述】:
我有以下疑问;
"SELECT goals_challenges.*,
products_services.id as psid,
products_services.url,
products_services.feature_benefit
FROM goals_challenges
LEFT JOIN products_services ON goals_challenges.id = products_services.goal_challenge_id
WHERE persona_id = :persona_id"
两个表都有一个“id”列,因此是“psid”别名。
但是,尽管 products_services 表中有两条记录与 goal_challenge_id 匹配,但只有第一行作为结果集的一部分返回。
编辑:正确的数据
目标挑战
id persona_id title item_category solution
173 14 Lead Gen business challenge advertising
产品服务
id goal_challenge_id url feature_benefit
1 173 www.testurl.com good for testing, mobile
2 173 www.google.com good for searching, well known
PHP 代码,包括查询;
public function findByPersonaId($persona_id)
{
try {
$this->dblayer->beginTransaction();
$stmt = $this->dblayer->prepare("SELECT goals_challenges.*, products_services.id as psid, products_services.url, products_services.feature_benefit from goals_challenges LEFT JOIN products_services ON goals_challenges.id = products_services.goal_challenge_id WHERE goals_challenges.persona_id = :persona_id");
$stmt->bindParam(':persona_id', $persona_id);
$stmt->execute();
$this->dblayer->commit();
$result_set = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result_set[] = $this->mapObject($row);
}
return $result_set;
} catch (PDOException $e) {
$this->dblayer->rollBack();
echo $e->getMessage();
exit;
}
}
public function mapObject(array $row)
{
$entry = new GoalChallenge();
$entry->setId($row['id']);
$entry->setPersonaId($row['persona_id']);
$entry->setTitle($row['title']);
$entry->setItemCategory($row['item_category']);
$entry->setDescription($row['description']);
$entry->setSolution($row['solution']);
$entry->setProductService(new ProductService($row['psid'], $row['id'], $row['url'], explode(',', $row['feature_benefit'])));
$entry->SetResearchChecklist($row['research_checklist']);
$entry->setSubtopics($row['subtopics']);
$entry->setKeywords($row['keywords']);
$entry->setStatus($row['status']);
return $entry;
}
我得到的回报
Array
(
[id] => 173
[persona_id] => 14
[title] => Lead Gen
[item_category] => Business Challenge
[solution] => Advertising
[product_service] =>
[research_checklist] => 0,0,0,0,0,0
[psid] => 1
[url] => www.google.com
[feature_benefit] => good for testing, mobile
)
编辑:好的,所以我已经计算出我期望的结果,它与另一个不在同一个 goalChallenge 对象中 - 显然是 PHP 中的东西 - 有什么想法吗?
我从goals_challenges 表中获取所有数据,但仅从products_services 表中获取第一行(id 1)。
我的查询有问题吗?我已经尝试添加“GROUP BY targets_challenges.id”,但它不会改变结果。
【问题讨论】:
-
persona_id 属于哪个表?
-
目标挑战表。 products_services 表没有 persona_id - 我认为这可能是问题所在,但为什么会从 products_services 表返回任何行?
-
也许问题在于你如何迭代结果集
-
products_services中goal_challenge_id的数据类型是什么?如果它是 varchar 类型,goal_challenge_id 数据值中可能会有一些额外的空间