JOIN不检索行

时间:2012-02-23 19:03:15

标签: php mysql

登录的用户userid = 8。我希望查询返回产品表中的所有行,但如果userid = 8已投票,则不显示相似或不喜欢的代码。

使用下面的查询,不会返回任何行。我不应该在投票表中插入每个用户ID(每个产品的用户太多)。这样做的正确方法是什么?

$query=  mysql_query("SELECT rate.voted as rvote, child.* FROM products child JOIN vote rate on child.id=rate.parentid WHERE rate.userid='8'") or die(mysql_error());

投票表

id | parentid |   userid |   voted  |
 1 |    1     |     6    |    1     |
 2 |    2     |     6    |    1     |
 3 |    1     |     4    |    1     |
 4 |    3     |     6    |    1     |

产品表

id |     name     |
 1 |     bottled  |
 2 |     grain    |
 3 |     milk     |
 4 |     bread    |

PHP

while($row=mysql_fetch_assoc($query)) {
$name = $row['name'];
$vote = $row['rvote'];

   echo $name;

   if($vote!=1) {
//like or dislike code
}



}

3 个答案:

答案 0 :(得分:2)

以下是使用8返回用户JOIN的结果的方法:

SELECT v.voted, p.*
FROM product p
LEFT JOIN vote v
  ON v.userid = 8
  AND v.parent_id = p.id
对于已投票的产品,

voted将为1,否则为NULL

使用产品表的id列上的索引和vote表上的列(userid, parent_id)的多列索引,它应该非常快。

答案 1 :(得分:0)

select * from products
where id not in (select parentid from vote where userid = 8);

答案 2 :(得分:0)

此查询将为您提供所需的结果:

select * from product where id not in (select id from vote where userid =8 and (voted = 0 || voted =1))