我想要的结果:
campaign 1
offer 1.1
offer 1.2
offer 1.3
(and so forth)
campaign 2
offer 2.1
offer 2.2
offer 2.3
(and so forth)
这些是我的表格:
campaign (tablename)
campaign_id (used)
campaign_name
offer (tablename)
offer_id
offer_parentid (uses category_id find which category the item is supposed to be paired
with.)
offer_name
我对使用两张桌子的经验不多,但我发现它对这种事情很有用。 我的问题是我已经尝试了我知道的PHP的每个方面,我无法得到我想要的结果。 这是我经过几个小时的血,汗和眼泪后的最终结果:
$get_campaign = mysql_query("SELECT * FROM campaign ORDER BY campaign_id DESC")
or die(mysql_error());
$get_offers = mysql_query("SELECT * FROM offers JOIN campaign ON offers.offer_parentid=campaign.campaign_id ORDER BY campaign_id DESC ")
or die(mysql_error());
while($row = mysql_fetch_array($get_campaign)){
echo $row['campaign_name']."</br>";
while($row = mysql_fetch_assoc($get_offers)){
echo $row['offer_name']."</br>";
}
}
结果变为:
Campaign 1
offer 1.1
offer 1.2
offer 2.1
offer 2.2
campaign 2
感谢您提供任何帮助
答案 0 :(得分:0)
您需要以第一个查询条件为第二个查询生成SQL:
$get_campaign = mysql_query("SELECT * FROM campaign ORDER BY campaign_id DESC")
or die(mysql_error());
while($row = mysql_fetch_array($get_campaign)){
echo $row['campaign_name']."</br>";
$get_offers = mysql_query("SELECT * FROM offers WHERE campaign_id = " . $row['campaign_id'] . " ORDER BY campaign_id DESC ")
or die(mysql_error());
while($offerRow = mysql_fetch_assoc($get_offers)){
echo $offerRow['offer_name']."</br>";
}
}
请注意,我假设您的广告系列表中的主键列是“id”。您也可以在一个带有连接的查询中执行此操作并且只有一个循环,但是根据数据的大小和您从第一个表中真正返回的数量,两个循环更适合性能。
答案 1 :(得分:0)
您可以使用一个查询:
$query = 'SELECT c.campaign_name, o.offer_name
FROM campaign c
INNER JOIN offers o ON (o.offer_parentid = c.campaign_id)
ORDER BY c.campaign_id';
现在循环搜索结果:
$campaign = '';
while($row = mysql_fetch_array($query)){
// only display the campaign name when its not $campaign
if ($row['campaign_name'] != $campaign){
echo $row['campaign_name']."</br>";
$campaign = $row['campaign_name'];
}
echo $row['offer_name']."</br>";
}
注意:我必须说你使用选择不当的列名。如果您参考商品表中的广告系列表,则应选择offers.campaign_id。原因是你现在知道你需要什么,但是当你得到更多的表和列时,很难在没有首先查看PHP代码的情况下选择表之间的正确列连接。它可以节省你(以及其他使用你的代码的人)很多时间。