通过显示错误3065(HY000)的MySQL查询与不同和顺序

时间:2017-09-28 09:53:49

标签: mysql sql-order-by distinct

我在我的机器上使用linux mint并尝试执行查询。执行后,显示错误

  

错误3065(HY000):ORDER BY子句的表达式#1不在SELECT列表中,引用列' shelterl_local.animal.changed'这不在SELECT列表中;这与DISTINCT

不兼容

我添加了行

[mysqld]
sql-mode=''

/etc/mysql/my.cnf文件中并重新启动mysql。但仍然得到同样的错误。我提到了许多解决方案,但对我来说没有任我的问题是

SELECT DISTINCT fs.etid AS etid FROM og_membership fs 
LEFT OUTER JOIN node animal ON animal.nid = fs.etid LEFT OUTER JOIN 
field_data_field_for_animal dfa ON dfa.field_for_animal_value = fs.etid 
LEFT OUTER JOIN node pastid ON pastid.nid = dfa.entity_id WHERE ( (fs.gid = 
464) OR 
(animal.nid IN   
(1196113,1211208,1218831,1243640,1254254,
1253603,1249890,1261729,1261282,1258378,1273745,1270760,
1279219,1276040,1276031,1275684,1288727,1289306,1300545,
1313770,1313761,1313755,1313746,1313330,1312388,1310673,
1309431,1315024,1333640,1328041,1323565,1327216,1330104,
1327786,1326810,1335812,1333094,1341309,1340358,1348088,
1351077,1351071,318214,1342698,1472755,1491527,1351652,1353488,
1507763,1342713)) )AND (fs.entity_type = 'node') 
AND (animal.type = 'animal') AND (animal.status = 1) AND (pastid.title LIKE 
'%A%') 
ORDER BY animal.changed DESC LIMIT 0,300;

是否可以永久删除此错误并执行查询?请帮忙

3 个答案:

答案 0 :(得分:1)

您的初始查询等同于以下内容:

SELECT field1 AS f1
FROM table t
--Joins and conditions
GROUP BY field1
ORDER BY field2 DESC LIMIT 0,300

这不具有逻辑意义,因为结果集中field1的每个值都可能具有与其关联的多个field2。您看到的错误是MySQL的说法,它无法弄清楚您想要做什么。一种解决方法是对field2的聚合进行排序,例如尝试以下方法:

SELECT field1 AS f1
FROM table t
--Joins and conditions
GROUP BY field1
ORDER BY MAX(field2) DESC   -- or AVG(field2), or MIN(field2), etc.
LIMIT 0,300

答案 1 :(得分:0)

您需要实际选择field2

    SELECT DISTINCT field1 AS f1,
    field2
    FROM table t
    --Joins and conditions
    ORDER BY field2 DESC LIMIT 0,300

更新:

我知道在同一个查询中使用DISTINCT和ORDER BY时有时会出现错误。为了解决这个问题,我会给animal.changed一个ALIAS,如[animal.changed],然后如果你ORDER BY [animal.changed],这不应该是错误。至少我知道这肯定适用于SQL服务器

E.G

    SELECT DISTINCT animal.changed AS [animal.changed]
    FROM .....
    ORDER BY [animal.changed]

这是非常基本的,但允许您在同一查询中使用DISTINCT和ORDER BY,这是您正在获得的当前错误。

答案 2 :(得分:-1)

如果选择一列,则只能对该列进行排序。如果需要按另一列排序,则必须在选择中包括此列。

//错误.....

$sql="Select DISTINCT Rubrika from tmp3 order by View desc limit 3";
$res_r=mysqli_query($Link, $sql);

//对!!!

$sql="Select DISTINCT Rubrika, View from tmp3 order by View desc limit 3";
$res_r=mysqli_query($Link, $sql);