简体   繁体   中英

SELECT sql statement that retrieves one row from a table and many related rows from other table

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

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); 

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

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.

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)

抱歉,评论中有错字... :)

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!

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