开发者

Select from MySQL table while ordering by IDs from another table

This might be something very simple to do. If so, I apologize. I'm still learning MySQL.

Say, I have two tables:

Table1:
`id` int autoincrement primary key
`Name` tinytext
`Phone` tinytext
`Date` etc.

and

Table2:
`id` int autoincrement primary key
`itmID` int

Each row in Table2 specifes the order at which elements should 开发者_Python百科be selected out of Table1. itmID field in Table2 is linked to id field in Table1.

So right at this moment to select elements from Table1 I do this:

SELECT * FROM `Table1`;

But how do you order them according to Table2, something like this?

SELECT * FROM `Table1` ORDER BY <itmID's in Table2> ASC;


If all ids of the Table1 have an entry on Table2 use an INNER JOIN, like this.

SELECT * FROM Table1 t1
INNER JOIN Table2 t2 ON t1.id = t2.itmID
ORDER BY t2.itmID

If not all of them have an entry, then use a LEFT JOIN, like this:

SELECT * FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.id = t2.itmID
ORDER BY t2.itmID


Select from the first table, join it to the second, and order by the second. Something like

SELECT * 
FROM   table1
LEFT JOIN table 2 on table.id = table2.id
ORDER by table2.itmID


Ryan's answer is almost right

SELECT *
FROM table1
INNER JOIN table2 on table1.id = table2.itmID
ORDER BY table2.id


http://dev.mysql.com/doc/refman/5.5/en/join.html

SELECT * FROM `Table1`
INNER JOIN `Table2` USING (`id`)
ORDER BY `Table2`.`itmID` ASC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜