I'm pretty new to SQL but hit a wall last night when I was experimenting on my website. I've been trying to figure it out now for hours with no luck, so here's my first post on Stack Overflow!
My issue is that I'm trying to sort a table of results, however what I need to sort by is from a different query from the main data. So I have a table of data that outputs fine, but I can't use ORDER BY to the field I want because it comes from a different query.
I have two tables:
character_
quest_globals
Data I need from the two tables:
character_.id
character_.name
character_.class
character_.level
quest_globals.charid (Same value as character_.id)
quest_globals.name
quest_globals.value
Ordered by: quest_globals.value
I would like to join these two tables so I can order the results how I like. Do I need to use UNION or JOIN for this?
character_
and quest_globals
have a common field as character_.id
is the same as quest_globals.charid
so I'm guessing I use this to join?
SELECT c.id, c.name, c.class, c.level, q.name, q.value
FROM character_ c
LEFT JOIN
quest_globals q
ON
q.charid = c.id
ORDER BY q.value
Also, you can give names to your columns like:
c.name as char_name, q.name as quest_name
so, it won't be so messy
SELECT character_.id,character_.name,character_.class,character_.level,quest_globals.name,quest_globals.value
FROM character_
LEFT JOIN quest_globals ON quest_globals.charid = character_.id
ORDER BY quest_globals.value
Query will be like this:
SELECT character_.id
character_.name
character_.class
character_.level
FROM character_
INNER JOIN quest_globals
ON character_.id=quest_globals.charid
ORDER BY quest_globals.value
hope it solves the column.