SELECT语句具有不同数量的列

时间:2014-01-19 21:05:58

标签: mysql sql

我尝试过使用下面的代码,然后说

  

使用的SELECT语句具有不同的列数

因为添加的距离列在第二个查询中更多。我如何解决这样的问题,或者我可以在没有距离列的情况下获得正确的订单吗?我非常感谢任何帮助。提前进行了解决。

SELECT * FROM
(
   SELECT * FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   WHERE u.empid = 123

   UNION

   SELECT * ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
   FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   HAVING distance < 25
   ORDER BY distance
) a
ORDER BY timestamp DESC

2 个答案:

答案 0 :(得分:2)

这是因为您的第一个SELECT和第二个SELECT列数不同,因为您在第二个Distance中引入了SELECT

因此,请尝试在第一个查询中将Distance设为null或0,如下所示。

SELECT * FROM
(
   SELECT *, 0 as Distance
   FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   WHERE u.empid = 123

   UNION

   SELECT *, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
   FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   HAVING distance < 25
   ORDER BY distance
) a
ORDER BY timestamp DESC

答案 1 :(得分:0)

您可以通过向第一个查询添加距离来解决此问题:

SELECT * FROM
(
   SELECT *, NULL as distance FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   WHERE u.empid = 123

   UNION

   SELECT *,  ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
   FROM user u
   INNER JOIN employee e ON (u.empid = e.empid)
   INNER JOIN awards a ON (u.empid = a.empid)
   HAVING distance < 25
   ORDER BY distance
) a
ORDER BY timestamp DESC;