mySQL query: for a given typeId, getting all entries with their answerCount
I have a mySQL table called entry. It has 2 test records in it:
SELECT * FROM entry WHERE typeId = 2
I have different types. For example when typeId = 2 that is a question. When typeId = 3 that is an answer. When an answer is inserted into this table the linkId column gets populated with the entryId of the question it is answering.
For example:
SELECT * FROM entry WHERE typeId = 3
As you can see both of these records are typeId = 3 and the linkId both point to entryId = 1.
In the following query I'm only getting the question that has answers associated to it.
SELECT SQL_CALC_FOUND_ROWS
entry.entryId, entry.entryText, entry.voteCount AS voteCount,
USER.userName, USER.fbId, COUNT(e2.entryId) AS answerCount
FROM entry
INNER JOIN USER ON entry.userId = USER.userId
INNER JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1
WHERE entry.active = 1
AND entry.typeId = 2
ORDER BY entry.voteCount DESC
According to the above statements I have 2 entries that are of typeId = 2. So I would really like this statement to return both entries but obviously the answerCount for the entry with out any answers would be 0.
Does anyone have any ideas with what I've shown you to fix this query to get the desired results?
UPDATE:
Based off of the suggestion below. I changed the inner join to a left join:
SELECT SQL_CALC_FOUND_ROWS DISTINCT
entry.entryId, entry.entryText, entry.voteCount AS voteCount,
USER.userName, USER.fbId
FROM entry
INNER JOIN USER ON entry.userId = USER.userId
LEFT JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1
WHERE entry.active 开发者_如何学编程= 1
AND entry.typeId = 2
ORDER BY entry.voteCount DESC
In this statement I took out the count statement (COUNT(e2.entryId) AS answerCount).
This is the result:
When I put in the COUNT statement it only returns the 1 record that returned when it was the inner join:
UPDATE:
I was able to get the rows to return properly by making sure the LEFT JOIN was correct and when I added a GROUP BY, then the row with 0 answers returned properly.
See my query below.
I think your second join on entry table should be a left join:
INNER JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1
should be:
LEFT JOIN entry AS e2 ON e2.linkId = entry.entryId AND e2.active=1
I actually got it to work...
Here is my updated statement:
SELECT e1.entryId, e1.entryText, e1.voteCount AS voteCount,
USER.userName, USER.fbId, COUNT(e2.linkId)
FROM entry e1
INNER JOIN USER ON e1.userId = USER.userId
LEFT JOIN entry e2
ON e2.linkId = e1.entryId
WHERE e1.active = 1
AND e1.typeId = 2
GROUP BY e1.entryId
ORDER BY e1.voteCount DESC
I added the LEFT JOIN as suggested but I also made sure the join was correct and the final piece of the puzzle was the GROUP BY. Once I put that in, I got my 2 rows that I was originally looking for.
Thanks for all the help!
精彩评论