php - Why does COALESCE order results in this way? -


i have table 3 columns, id, comment, , parent. if parent id null, comment root comment, , if not, means comment reply another. use following query:

select *   `comment`  order coalesce( parent, id ) desc  limit 0 , 30 

this query orders last inserted comment it's replies, don't understand logic. why ordered way?

enter image description here

the coalesce() function returns first non-null argument received. so, if go through each row , compare parent/id column, you'll see ordered this:

7 (because parent null) 2 (because parent null) 2 (parent not null, used) 1 (because parent null) 1 (parent not null, used) 1 (parent not null, used) 

which in descending order, specified.


i suspect there may confusion here. let me reiterate. coalesce(parent, id) return first value out of 2 not null. if parent not null, returned. if null, falls on id , returns that. if @ list of rows side side , see return values, may more clear:

| parent | id | return_value | +--------+----+--------------+ |  null  | 7  |       7      | |  null  | 2  |       2      | |  2     | 4  |       2      | |  null  | 1  |       1      | |  1     | 3  |       1      | |  1     | 5  |       1      | |  1     | 6  |       1      | 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -