我在民意调查脚本中工作,我有两个表{hs_questions_q} {hs_answers_ans},第一个存储了问题,第二个存储了答案
我使用这个sql语句来检索数据
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
我很奇怪,我无法在我的PHP代码中处理这个查询如何仅从问题表和答案表返回最后一行,但我需要从问题表中检索最后一行并且与答案表相关的所有行
答案 0 :(得分:1)
这将在表中的每个问题返回1行而不是答案的num行:
我假设结构:
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
稍后,您可以将其拆分为'#'在php端检索结果后。
如果超过允许的数据包大小,您可能会收到截断的答案。你可以通过
解决它SET SESSION group_concat_max_len = 6000(any threshold);
答案 1 :(得分:0)
我认为这大致是你正在寻找的东西:
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
我不知道active_q和home_q是否属于问题表或答案
答案 2 :(得分:0)
这是因为你试图抓住一行并加入多行不同的数据...我不认为这会有效。
我会选择问题,然后使用问题中的ID分别获取所有答案。
答案 3 :(得分:0)
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)
抱歉,评论中有一些错字...... :)
答案 4 :(得分:0)
此查询应该为您提供所需的结果:
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'
);
希望它有所帮助!