0

I need to find, for example, a user by his posts id. Database with users and posts may look like this:

Users:

 id | username | password
 ---+----------+---------
   1|      John|     ****
   2|       Eve|     ****
   3|      Rich|     ****

Posts:

 id | author_id | contents
 ---+-----------+---------
   1|          1| I'm John
   2|          2|  I'm Eve
   3|          3| I'm Rich
   4|          3| It's Rich not rich, keep that on mind...

My situation is just slightly different from post<->user situation, because in my case, I don't need any information about post.
So according to the above, and with help of some random posts I found (with MySql problems I never know what to search on google) I thought my query should look like this:

SELECT username, id 
FROM `user` 
WHERE id IN (SELECT author_id FROM `post` WHERE author=$MYID)

This does not work, so I guess more magic than mysterious IN statement will be needed.

4

2 回答 2

0

如果我理解正确,这可能会起作用:

SELECT username, id FROM `user` WHERE id IN (SELECT author_id FROM `post` WHERE id=$MYID)
于 2013-09-01T20:51:30.267 回答
0

Is the problem post versus posts and user versus users?

SELECT username, id
FROM `users`
WHERE id IN (SELECT author_id FROM `posts` WHERE author=$MYID);

More importantly, though, earlier versions of MySQL (up to 5.6.x) do a poor job of opitimizing in queries. You can rewrite this as:

SELECT username, id
FROM `users` u
WHERE exists (SELECT 1 FROM `posts` p WHERE author=$MYID and p.author_id = u.id)
于 2013-09-01T20:58:36.003 回答