在子查询中按列排序最终结果

时间:2016-09-23 12:05:04

标签: mysql

我有一个基于子查询结果查询的查询。我想通过子查询中的列来排序,但是通过查看类似的问题我可以理解,你真的不应该在子查询中使用ORDER BY(这使得这个查询不正确)。

我有什么方法可以使用别名或其他方法做到这一点?

在子查询表中有一个名为“lastUpdated”的列,我想从主查询表中对结果进行排序。

请参阅下面我的尝试查询:

SELECT * FROM TrackedEntityInstance 
WHERE localId IN 
   (SELECT DISTINCT localTrackedEntityInstanceId FROM Enrollment
    WHERE program IS 'SSLpOM0r1U7' AND orgUnit IS 'gGl6WgM3qzS' 
    ORDER BY lastUpdated ASC);`

3 个答案:

答案 0 :(得分:2)

您可以使用如下所示的连接...我认为它也更快..

.
.
.
I0923 12:08:37.121116 2341 sgd_solver.cpp:106] Iteration 1300, Ir = 0.01
*** Aborted at 1474628919 (unix time) try "date -d @1474628919" if you  are using GNU date ***
PC: @                0x0 (unknown)
*** SIGBUS (@0x7ddea45000) received by PID 2341 (TID 0x7faa9fdf70) from  PID 18446744073149894656; stack trace: ***
    @       0x7fb4b014e0 (unknown)
    @       0x7fb3ebe8b0 (unknown)
    @       0x7fb4057248 (unknown)
    @       0x7fb40572b4 (unknown)
    @       0x7fb446e120 caffe::db::LMDBCursor::value()
    @       0x7fb4587624 caffe::DataReader::Body::read_one()
    @       0x7fb4587a90 caffe::DataReader::Body::InternalThreadEntry()
    @       0x7fb458a870 caffe::InternalThread::entry()
    @       0x7fb458b0d4 boost::detail::thread_data<>::run()
    @       0x7fafdf7ef0 (unknown)
    @       0x7fafcfde48 start_thread
Bus error

我假设您在SELECT * FROM trackedentityinstance t1 JOIN ( SELECT DISTINCT localtrackedentityinstanceid, lastupdated FROM enrollment WHERE program IS 'SSLpOM0r1U7' AND orgunit IS 'gGl6WgM3qzS' ) t2 ON t1.id=t2.localtrackedentityinstanceid ORDER BY t2.lastupdated ASC 表中有id字段。如果没有,请调整查询并试一试。

答案 1 :(得分:0)

试试这个:

SELECT * FROM TrackedEntityInstance 
WHERE localId IN 
      (SELECT localTrackedEntityInstanceId, MAX(lastUpdated ) AS LastUpdated
       FROM Enrollment
       WHERE program IS 'SSLpOM0r1U7' AND orgUnit IS 'gGl6WgM3qzS' 
       GROUP BY localTrackedEntityInstanceId );`

答案 2 :(得分:0)

您可以使用MySQL FIELD()

参考:http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_field

首先,您需要取出子查询并根据需要在localTrackedEntityInstanceId中创建逗号(,)分隔的字符串(可以使用GROUP_CONCAT())

其次,您可以在FIELD()函数中使用逗号分隔的字符串作为

ORDER(ASC)

希望这适合你。