MySQL联合和命令的帮助

时间:2011-09-02 03:30:50

标签: mysql sql sql-order-by union

下面的代码有效,但是当我通过id将Order更改为Order by s.id时,我收到此错误

  

'order clause'中的未知列's'id'

$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";

如何更改代码以便按顺序排序s.id,这是订阅表的ID?

2 个答案:

答案 0 :(得分:2)

MySQL正在尝试将ORDER BY应用于UNION,但UNION只有child列(此处没有child.前缀),UNION中没有s.id 。但你可以添加一个:

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

你需要给它一个别名,因为UNION将剥离表名或别名前缀。如果sid中有child列,则使用其他内容作为s.id的别名。

答案 1 :(得分:0)

  

“INNER JOIN subscribe s”

看起来好像你想要:

INNER JOIN `subscribe` AS `s`

如果不起作用,请发布输出:

DESCRIBE subscribe;