我有两张桌子。首先是产品,第二个是订单
产品
id |Product name
01 |Computer
02 |Mobile
03 |Tablet
和订单的第二个表
p_id | username
02 | Joe
02 | Mike
01 | Joe
03 | Tomy
现在我想向用户展示那些尚未被用户购买的产品 假设登录用户名是Mike
$username = "Mike";
$get = mysqli_query($db, "SELECT e.id
FROM `products` AS e INNER JOIN `order` AS u ON u.p_id = e.id WHERE e.username != '$username' ");
echo mysqli_num_rows($get);
Result 3;
以上查询计算用户名不是mike的所有订单并显示结果..我只想要那些“Mike”未购买的产品列表
答案 0 :(得分:3)
您必须进行反加入
SELECT * FROM product p
WHERE NOT EXISTS (
SELECT 1 FROM order o WHERE o.username = 'Mike' AND p.id = o.p_id
)
有关https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html
的更多信息答案 1 :(得分:0)
我不确定我是否理解你的问题,但我认为你想要这样做:
$notThisUser = "Mike";
$sql = $mysqli->prepare("SELECT productname FROM product
WHERE id IN (SELECT p_id FROM order WHERE username != ?)");
$sql->bind_param("s", $notThisUser);
$sql->execute();
$sql->bind_result($productName);
while ($sql->fetch()) {
echo $productName;
}
答案 2 :(得分:0)
我想这就是你的目标。
$username = "Mike";
$selectQuery = "select p.id from product
inner join oder AS o on o.p_id=p.id where o.username <> :username";
$statement = $dbh->prepare($selectQuery);
$statement->bindValue(":username", $username);
$statement->execute();
$data = $statement->fetchAll(\PDO::FETCH_ASSOC);
答案 3 :(得分:-1)
你应该选择* FROM product
WHERE id
NOT IN(SELECT p_id
FROM order
WHERE user_name
=&#39; Mike&#39 ;)那就是