与内连接联合,mysql错误

时间:2014-02-05 23:24:20

标签: mysql join mysqli union

(SELECT * FROM app_detailsvvv as dtable INNER JOIN new_apps ON 
new_apps.trackId=dtable.trackId WHERE primaryGenreName='Games'
AND composed='1' AND new_apps.top>0)
UNION (SELECT * FROM app_detailsvvv as dtable WHERE primaryGenreName='Games')
LIMIT 12

错误:

#1222 - The used SELECT statements have a different number of columns

在new_apps上有些字段不在app_detailsvvv中,我怎样才能以某种方式屏蔽联合中的第二个查询。

编辑:

(SELECT dtable.* FROM app_detailsvvv as dtable INNER JOIN new_apps ON new_apps.trackId=dtable.trackId WHERE primaryGenreName='Games' AND composed='1' AND new_apps.top>0) UNION (SELECT * FROM app_detailsvvv as dtable WHERE primaryGenreName='Games') LIMIT 12

当我添加ORDER BY new_apps.top ASC时,我收到了这个新错误:

#1250 - Table 'new_apps' from one of the SELECTs cannot be used in global ORDER clause

2 个答案:

答案 0 :(得分:1)

我认为您不需要union,只需left outer join

SELECT dtable.*
FROM app_detailsvvv as dtable LEFT OUTER JOIN
     new_apps
     ON new_apps.trackId = dtable.trackId and
        composed = '1' AND new_apps.top > 0
WHERE dtable.primaryGenreName = 'Games'
LIMIT 12;

嗯,这可能会返回重复项,您可以使用select distinct dtable.*删除它。

但是等等。除了返回第一个表中的所有行之外,此查询实际上没有做任何其他操作。我怀疑你想要返回12行,优先考虑匹配的行。如果是这种情况,那么您想要的查询是:

SELECT dtable.*
FROM app_detailsvvv as dtable LEFT OUTER JOIN
     new_apps
     ON new_apps.trackId = dtable.trackId
WHERE dtable.primaryGenreName = 'Games'
GROUP BY dtable.trackId   <-- or whatever the unique id is on the table
ORDER BY (composed = '1' AND new_apps.top > 0) desc
LIMIT 12;

答案 1 :(得分:0)

试试这个:

(SELECT dtable。* FROM app_detailsvvv as dtable INNER JOIN new_apps ON new_apps.trackId = dtable.trackId WHERE primaryGenreName ='Games' AND composition ='1'AND new_apps.top&gt; 0) UNION(SELECT * FROM app_detailsvvv as dtable WHERE primaryGenreName ='Games') 限制12