[英]How to select multiple rows from two tables that have a common column?
I have three tables. 我有三张桌子。
system_modules system_lectures system_tutorials system_modules system_lectures system_tutorials
I want to select data from system_lectures and system_tutorials with a WHERE clause on system_modules. 我想使用system_modules上的WHERE子句从system_lectures和system_tutorials中选择数据。
So far I have this: 到目前为止,我有这个:
SELECT l.lecture_name, t.tutorial_name
FROM system_modules m
JOIN system_lectures l ON m.moduleid = l.moduleid
JOIN system_tutorials t ON m.moduleid = t.moduleid
WHERE m.moduleid = 1
In the database at the moment, there are 1 record in each table. 目前,在数据库中,每个表中都有1条记录。 1 lecture, 1 tutorial.
1个讲座,1个教程。 The query returns the data.
查询返回数据。 But it returns just one row, with the data from both tables side by side.
但是它只返回一行,两个表的数据并排。 I want it to return the data in two rows, as if you would just add up the two tables together.
我希望它返回两行数据,就像您将两个表加在一起一样。
Any form of query where you perform a JOIN will generally return the data all together in a single row. 执行JOIN的任何形式的查询通常都会在一行中一起返回所有数据。 The general idea of the join is to match data between two or more tables into a single output row.
连接的一般想法是将两个或多个表之间的数据匹配到单个输出行中。
If you want to "concatenate" results from two queries, you are looking for a UNION: http://dev.mysql.com/doc/refman/5.6/en/union.html 如果要“连接”两个查询的结果,则需要一个UNION: http : //dev.mysql.com/doc/refman/5.6/en/union.html
However this will only work when the columns are the same. 但是,这仅在列相同时起作用。 If the columns are different and you want separate rows then what you really need to do is simply run multiple queries.
如果列不同,并且您想要单独的行,那么您真正需要做的就是简单地运行多个查询。
You can use a union
query to do this: 您可以使用
union
查询来执行此操作:
SELECT l.lecture_name
FROM system_modules m
JOIN system_lectures l ON m.moduleid = l.moduleid
WHERE m.moduleid = 1
UNION ALL -- remove the ALL keyword if you need to eliminate duplicates
SELECT t.tutorial_name
FROM system_modules m
JOIN system_tutorials t ON m.moduleid = t.moduleid
WHERE m.moduleid = 1
This query will join the two sets together. 该查询将两个集合连接在一起。 It relies on the data type being the same for the columns
l.lecture_name
and t.tutorial_name
. 它依赖于
l.lecture_name
和t.tutorial_name
列的数据类型相同。 If they're not, and can't be implicitly converted you need to manually convert them to compatible types. 如果不是,并且不能隐式转换,则需要手动将它们转换为兼容类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.