2014-01-29 44 views
0

这是很难解释和我的英语不起作用,但它是: 我有两个数据表:“节点”和“记录”。 在节点表我保存的数据的问题和答案SQL查询来联合一个数据表与另一个数据表

节点的数据: | id |名称|键入|

记录: | id | questionid | answerid |

我试过尽管不成功,但要做一个sql查询给我的所有记录的数据,但与答案的名称和id的问题intead。 总之,我需要的是:records.id,nodes.name(问题),nodes.name(回答)

+0

没有足够的信息。节点和记录如何相关?显示您的数据的一些示例。 – sashkello

+0

records.questionid和records.answerid与节点 – Marcelo

回答

2
SELECT 
    questions.name AS questionname 
    answers.name AS answername 
FROM records 
    INNER JOIN nodes AS questions ON records.questionid=questions.id 
    INNER JOIN nodes AS answers ON records.answerid=answers.id 
+0

的ID相关,非常感谢,工作得很好! – Marcelo

1

您可以使用此查询:

SELECT q.name AS question, a.name AS answer 
FROM records r 
LEFT JOIN nodes q ON q.id = r.questionid 
LEFT JOIN nodes a ON a.id = r.answerid 
WHERE 1 

对于此查询我建立以下模式:

CREATE TABLE nodes (
id int auto_increment primary key, 
name varchar(30), 
type int(1)); 

INSERT INTO nodes (name, type) VALUES 
('Is it a question 01', 0), 
('Is it a question 02', 0), 
('This is an answer 01', 1), 
('This is an answer 02', 1), 
('This is an answer 03', 1); 

CREATE TABLE records (
id int auto_increment primary key, 
questionid int(11), 
answerid int(11)); 

INSERT INTO records (questionid, answerid) VALUES 
(1, 3), (1, 4), (1, 5), (2, 4), (2, 5); 

SQL小提琴:http://sqlfiddle.com/#!2/bfd340/1

相关问题