如何将子查询中的order by子句的结果应用于主查询

时间:2015-11-12 10:12:10

标签: mysql

我有2个表,这些表由名为MID的列链接。 我想从第一个表中获取名称,但序列在第二个表中提到。 我的查询如下:

select name from table1 where MID in(select MID from table2 where CID="100" ORDER BY sequenceNum);

如果我只运行括号内提到的查询,那么我得到按顺序排序的数据。 但是上面的查询是从db中获取数据,而不是按顺序排列。可能是什么问题?

2 个答案:

答案 0 :(得分:0)

我认为这可以解决问题......

SELECT name FROM table1 
INNER JOIN table2 ON Table2.MID = table1.MID AND CID="100" 
ORDER BY
  table2.sequenceNum

答案 1 :(得分:0)

You want merge two tables and order results by merged table:

SELECT table1.name
FROM table1
LEFT JOIN table2 ON (table2.MID = table1.MID)
WHERE table2.CID = "100"
ORDER BY table2.sequenceNum;

or

SELECT table1.name
FROM table1
  LEFT JOIN table2 ON (table2.MID = table1.MID AND table2.CID = "100")
ORDER BY table2.sequenceNum;

If you want get field from concrete table, use table prefix like table1.name