Reputation: 822
I working in a poll script, i have two tables {hs_questions_q}{hs_answers_ans} the first one stored the question and the second stored its answers
i used this sql statement to retrieve the data
SELECT * FROM hs_questions_q INNER JOIN hs_answers_ans ON id_q=idq_ans WHERE active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1
what i was wonder and i can't deal with in my php code is how that this query returned the last row only from the the question table and answers table, but i need to retrieve the last row from the question table and all rows related to it from the answers table
Upvotes: 1
Views: 328
Reputation: 9300
This will return 1 row per question in the table not as the num rows of answers:
I assume the structure:
hs_questions_q (id,desc)
hs_answers_ans(id,desc)
SELECT question.desc, group_concat(hs_answers_ans.desc SEPARATOR '#')
FROM (select *
from hs_questions_q
where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1) question
INNER JOIN hs_answers_ans ON id_q=idq_ans
group by question.id
result:
question1 | Answer1#Answer2#Answer3
Later, you can split it by '#' after retrieving the result on the php side.
You might get truncated answers if it exceeds the allowed packet size. You can solve it by,
SET SESSION group_concat_max_len = 6000(any threshold);
Upvotes: 1
Reputation: 6645
This query should give you the desired result:
SELECT *
FROM `hs_questions_q`
INNER JOIN `hs_answers_ans` ON `id_q` = `idq_ans`
WHERE `idq_ans` = (
SELECT MAX(`id_q`)
FROM `hs_questions_q`
WHERE `active_q` ='1'
AND `home_q` ='1'
);
Hope it helps!
Upvotes: 0
Reputation: 11254
select * from hs_answer_ans where idq_ans in (select id_q from hs_questions_q where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1)
Sorry some typo was there in comment...:)
Upvotes: 0
Reputation: 1172
Its because you are trying to grab one row and join it with more than one row of different data... I don't think that will work.
I would select the question and then use the id from the question to grab all the answers separately.
Upvotes: 0
Reputation: 14864
I think it's roughly what you're looking for:
SELECT * FROM
(select *
from hs_questions_q
where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1) question
INNER JOIN hs_answers_ans ON id_q=idq_ans
I don't know whether active_q and home_q belong to question table or answers
Upvotes: 0