Reputation: 193
I have three tables.
system_modules system_lectures system_tutorials
I want to select data from system_lectures and system_tutorials with a WHERE clause on system_modules.
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 lecture, 1 tutorial. 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.
Upvotes: 0
Views: 1275
Reputation: 44881
You can use a union
query to do this:
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
. If they're not, and can't be implicitly converted you need to manually convert them to compatible types.
Upvotes: 0
Reputation: 1892
Any form of query where you perform a JOIN will generally return the data all together in a single row. 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
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.
Upvotes: 1