0

I have a script where members login and read posts by catagory that I have in Table called posts, then they click a button and an entry is inserted into Table called postsread collecting the postname, their memberid, and the date showing that it had been read by them. What I am looking for is a query that will display to them only the posts that they have not already read.

**Tables**         **Fields**
posts          id, name, date, from, topic, info, cat
postsread      id, postname, memberid, date
users          id, memberid, pass, fname, lname, email

Sessions is already holding their $_SESSION['memberid'], but am unsure of how to query between the two tables to get what I'm looking for. It would be like: Show all posts in Posts except those in Postsread with the members memberid next to the corresponding postname. I am using php version 5.3, and mysql 5.0.96.

I am using the following to display posts from database:

$sql=mysql_query("SELECT * FROM posts WHERE cat='1' ORDER BY date DESC");

But this does not differentiate between if the member has clicked stating they have seen them yet or not.

I have looked many places and see examples that are close but just cant get any to fit what I am needing. I don't fully understand how to write this. I have tried many with no success. If you need extra description please ask. Thank you for your time.

4

2 回答 2

1

您需要JOIN针对表构造条件posts_read,或使用IN子句将它们排除在外。您应该非常小心您的索引,因为这些类型的查询可能会变得非常缓慢并且数据库密集型的数据量非常大。

SELECT * FROM posts WHERE cat=:cat AND name NOT IN (SELECT postname FROM postsread WHERE memberid=:memberid)

这里:cat:memberid是适当值的占位符。使用 PDO,您可以直接绑定到使用该execute函数的那些。

需要注意的是,加入字符串比加入id类型值要慢得多。您可能希望从中引用您的postsread表。idposts

于 2013-05-13T21:20:00.890 回答
0

sql=mysql_query("SELECT * FROM posts WHERE cat='1' AND name NOT IN (SELECT postname FROM postsread WHERE memberid='$memberid') ORDER BY date DESC") or die (mysql_error());

塔德曼的回答是对的。我在代码中有一些不应该存在的东西,但找不到它。最终我只是重写了这个东西并且它起作用了。以上对我有用,我感谢 Tadman 的帮助。

于 2013-05-19T20:58:57.617 回答