MySQL union and order by help

限于喜欢 提交于 2019-12-25 04:27:24

问题


The below code works but when i change Order by id to Order by s.id, i get this error

Unknown column 's.id' in 'order clause'

$construct =  "SELECT child.* FROM products child LEFT JOIN products parent on parent.name=child.parent INNER JOIN subscribe s ON (s.productid = parent.id) WHERE s.username='$logged' AND s.type='0'
        UNION
        SELECT child.* FROM products child LEFT JOIN products parent on parent.sid=child.sid INNER JOIN subscribe s ON (s.productid = parent.id) WHERE s.username='$logged' AND parent.keyword != child.name AND s.type='1'
        ORDER BY s.id DESC";

How can i change the code so it is ordered by s.id, which is the subscribe table's id?


回答1:


MySQL is trying to apply the ORDER BY to the UNION but the UNION only has the child columns (without the child. prefix at that), there is no s.id in the UNION. But you can add one:

SELECT child.*, s.id as sid ...
UNION
SELECT child.*, s.id as sid ...
ORDER BY sid DESC

You need to give it an alias as the UNION will strip off the table name or alias prefix. If there is an sid column in child then use something else as the alias for s.id.




回答2:


"INNER JOIN subscribe s"

It looks like maybe you want:

INNER JOIN `subscribe` AS `s`

if that doesn't work, please post the output of:

DESCRIBE subscribe;


来源:https://stackoverflow.com/questions/7278959/mysql-union-and-order-by-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!