简体   繁体   English

SQL查询连接结果列

[英]SQL query to join columns in result

I'm a complete SQL noob and have no idea how to utilize JOINs. 我是一个完整的SQL新手,不知道如何利用JOIN。 If someone could help with this query, it would be great. 如果有人可以帮助进行此查询,那就太好了。

I have a table questions which contains two columns: queid and que . 我有一个表questions ,其中包含两列: queidque Another table options , contains the corresponding options for the questions, and has columns optionid , queid , option . 另一个表options ,包含问题的相应选项,并具有列optionidqueidoption

How can I do a SELECT statement such that I can join both tables together based on queid ? 如何执行SELECT语句,以便可以基于queid将两个表连接在一起?

Something like: 就像是:

SELECT * from questions,options where queid=1

You should try this: 您应该尝试这样:

SELECT que.*, opt.* FROM questions que
INNER JOIN options opt ON que.queid = opt.queid
WHERE que.queid = 1

INNER JOIN loads questions and options having at least one corresponing record in every table. INNER JOIN加载在每个表中至少具有一个对应记录的问题和选项。

If you need to get all questions (even the ones not having options) you could use 如果您需要获得所有问题(甚至没有选择的问题),可以使用

SELECT que.*, opt.* FROM questions que
LEFT JOIN options opt ON que.queid = opt.queid
WHERE que.queid = 1

LEFT JOIN always loads questions and, if they have options, their options too; LEFT JOIN总是会加载问题,如果有选项,也会加载选项。 if not you get NULL for options columns. 如果不是,则选项列为NULL。

可能是

SELECT * FROM questions q JOIN options o ON q.queid=o.queid WHERE q.queid=1
SELECT q.*,o.* FROM questions q 
JOIN options o ON  q.queid = o.queid
WHERE q.queid = 1
SELECT *
FROM questions
JOIN options ON questions.queid = options.queid
WHERE questions.queid = 1

You can join two related tables using the column that they have in common. 您可以使用它们共有的列来联接两个相关的表。

in your case you can write : 您可以写:

SELECT * FROM Questions as Q INNER JOIN Options O ON Q.queid=O.queid WHERE Q.quid=1

You can also omit the where part like this : 您也可以省略where部分:

 SELECT * FROM Questions as Q INNER JOIN Options O ON Q.queid=O.queid AND Q.quid=1

There are different kind of joins : 有不同类型的联接:

INNER

OUTER(Left,Right,Full) 外(左,右,全)

By inner join you mean that only records that are common in both tables are returned When you use outer join all the records on the given side are return plus the records that have corresponding values on the other side otherwise instead of the other side values you will get null. 内部联接是指只返回两个表中共有的记录。使用外部联接时,将返回给定端的所有记录以及在另一端具有相应值的记录,否则将返回另一端的值。获得空值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM