我有这些表:
表格交易
表addonlist
表插件
我想echo
addons
上的所有项目,并查看表 addons
中的 addon_id
是否与 匹配>laddon_id
来自表 addonlist
并使用给定的 transac_id
向跟踪的项目添加注释。
我有这段代码,我可以对 addonlist
中找到的项目进行注释,但它回显
来自 的相同项目>插件
。
$getaddons = mysql_query("SELECT * FROM addons LIMIT 10");
while($rows = mysql_fetch_assoc($getaddons)){
$addonid = $rows['addon_id'];
$addondesc = $rows['description'];
$addonprice = $rows['price'];
$addonstat = $rows['status'];
$checkaddon = mysql_query("SELECT * FROM transactions t, addonlist al WHERE t.transac_id='44005' and t.transac_id=al.transac_id");
while($rows = mysql_fetch_assoc($checkaddon)){
$caddonid = $rows['laddon_id'];
if(mysql_num_rows($checkaddon) and $addonid == $caddonid){
echo "$addondesc already in your list"; // NOTE: item is already in your list
}
}
echo "<strong>$addondesc </strong><button>Add to list</button>";
}
这将显示(我的期望):
Coke 1 Litre - already in your list
Tuna Sandwich - already in your list
Hotdog Sanwich - add button
Chicken Sandwich - add button
Ham & Egg Sandwich - add button
Ham & Cheese Sandwich - add button
Grilled Cheese Burger - add button
Clubhouse Sandwich - add button
Goto - add button
Arrozcaldo - add button
但它显示的内容:
Coke 1 Litre - already in your list
Coke 1 Litre - add button `// This wouldn't be appearing`
Tuna Sandwich - already in your list
Tuna Sandwich - add button `// This wouldn't be appearing`
Hotdog Sanwich - add button
Chicken Sandwich - add button
Ham & Egg Sandwich - add button
Ham & Cheese Sandwich - add button
Grilled Cheese Burger - add button
Clubhouse Sandwich - add button
Goto - add button
Arrozcaldo - add button
编辑:
如果我的数据库结构
有问题或者只是我的代码
,请告诉我。
最佳答案
使用LEFT JOIN
在一个查询中获取所有内容。对于不在 addonlist
中的插件,您将从 addonlist
中获得列的 NULL
,并且您可以在循环中对其进行测试。
$getaddons = mysql_query("SELECT a.addon_id, a.description, a.price, a.status, l.laddon_id
FROM addons AS a
LEFT JOIN addonlist AS l ON a.addon_id = l.laddon_id AND l.transac_id = '44005'
LIMIT 10");
while ($rows = mysql_fetch_assoc($getaddons)) {
$addonid = $rows['addon_id'];
$addondesc = $rows['description'];
$addonprice = $rows['price'];
$addonstat = $rows['status'];
if ($rows['laddon_id']) {
echo "$addondesc already in your list";
} else {
echo "<strong>$addondesc </strong><button>Add to list</button>";
}
}
似乎不需要加入交易
,因为您没有使用该表中的任何内容。
关于php - 在 while 循环 mysql 中加入 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103934/