简体   繁体   中英

Union with inner join, mysql error

(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

error:

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

on new_apps there are fields that are not in app_detailsvvv, how can I mask for the second query in the union somehow.

edit:

(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

worked yet when I add ORDER BY new_apps.top ASC I get this new error:

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

I don't think you need a union , just a 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;

Hmmm, this might return duplicates, which you can get rid of using select distinct dtable.* .

But wait. This query really isn't doing anything other than returning all the rows in the first table. I suspect that you want to return 12 rows, with a priority given to the ones with a match. If that is the case, then the query you want is:

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;

Try this:

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM