[英]How to get values from two tables in which one column in each table contains similar value?
I have two tables the queries are given below 我有两个表,查询如下
db.execSQL("CREATE TABLE IF NOT EXISTS allquestions (num_id INTEGER PRIMARY KEY NOT NULL, questions TEXT NOT NULL,catogery TEXT NOT NULL,age INT NOT NULL)" );
db.execSQL("CREATE TABLE IF NOT EXISTS answers (num_id INTEGER PRIMARY KEY NOT NULL,questionid INT NOT NULL,answer TEXT NOT NULL)" );
Here the num_id in allqestions contains the question number and the answers are there in the table(answers) column answer.In the answer column the questionid contains the question number for the answer.So what I want is how to write the query to get questions from allquestion and its answers from table answer. 在这里,所有问题中的num_id包含问题号,并且答案在表(answers)列的答案中。在答案列中,questionid包含答案的问题号。所以我想要的是如何编写查询以获取问题从allquestion及其表答案中得到答案。
我认为您需要它。
select questions,answers from questions que,answers ans where que.num_id=ans.questionid;
You have to apply the join on both tables. 您必须在两个表上应用联接。
SELECT
allquestions.`num_id`,allquestions.`questions`,answers.questionid,
answers.answer from allquestions JOIN answers ON allquestions.`num_id`
= answers.questionid
Try the following. 尝试以下方法。 I hope you are looking for the same.
希望您也一样。
Give a row_number for each group, then use a CASE
statement. 为每个组指定一个row_number,然后使用
CASE
语句。
Query 询问
select t1.questionid,a.questions,
max(case when t1.row_number=1 then t1.answer else 0 end) as answer1,
max(case when t1.row_number=2 then t1.answer else 0 end) as answer2,
max(case when t1.row_number=3 then t1.answer else 0 end) as answer3
from allquestions a
join (
SELECT @row_number:=CASE WHEN @questionid=questionid
THEN @row_number+1
ELSE 1
END AS row_number,
@questionid:=questionid AS questionid,answer
FROM answers,
(SELECT @row_number:=0,@questionid:='') AS t
ORDER BY questionid
)t1
on a.num_id=t1.questionid
group by t1.questionid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.