简体   繁体   中英

Combining two MySQL queries into one

In my database, I have two tables: Replies and Threads.

I'm trying to make a Contributions page showing what threads users have started or replied to.

Inside Replies are "ThreadId" and "Poster" which specify the Id of the thread it was replied to, and each row in Threads has an Id column as well as a "Poster" column.

I'm trying to make a query to get the rows of all THREADS in which a user has either posted or posted in.

Example:

$myUsername = "Bob";
$q = mysql_query("SELECT * FROM `Threads` WHERE `Poster`='$myUsername'
OR (another query to find if they had a row in Replies matching `ThreadId`='$tid'
AND `Poster`='$myUsername')");

Thanks

You will need to use an IN clause to specify that the thread id should be in those returned by a query in the replies table. Something like this is I understand correctly the structure of your tables.

SELECT * FROM Threads WHERE Poster = $myUsername OR Id IN (
SELECT ThreadId FROM Replies WHERE Poster = $myUsername
)

Using Christina's solution probably won't result in a very efficient query. The following should be better:

SELECT * 
FROM Threads t1
WHERE t1.Poster='$myUsername'
UNION
SELECT *
FROM Threads t2
INNER JOIN replies r
ON t2.id=r.thread_id
WHERE t2.Poster<>'$myUsername'
AND r.Poster='$myUsername';

However:

1) do you really need all the columns from the threas table? Even if you do, using '*' is messy

2) you are still going to get duplicates if the user made more more than one reply - but this can't be fixed while you are using '*'

3) the query will still be slow eith large amounts of data if you don't have an index on poster in both tables.

I have done this differently. The two queries provided returned duplicates and what not, so I've decided to go a little longer way.

What I did:

1) Go through each of the user's replies, and get the thread id

2) Build a query string using these IDs, eg "OR Id=$threadId OR Id=$threadId2" etc

3) Put the query string into a thread query such as SELECT * FROM Threads WHERE Poster=$user $queryString2

4) Solution. :)

Try this:

You can use LEFT OUTER JOIN instead of IN operator

SELECT T.* 
FROM Threads T 
LEFT OUTER JOIN Replies R ON T.Id = R.ThreadId AND R.Poster = $myUsername
WHERE T.Poster = $myUsername OR R.Id IS NOT NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM