简体   繁体   中英

WHERE clause with inner join

I have the following query to count the amount of devices in my database. I try to add a WHERE clause to only select the device and count with the name "iphone".

SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices WHERE device='apple'
CROSS JOIN (
SELECT count( * ) AS total
FROM devices
)x
GROUP BY 1 

I tried to construct different queries, but they all result in a mysql error. What is the correct position of the WHERE clause?

WHERE 谈到FROM之前GROUP BY

SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices 
INNER JOIN (
SELECT count( * ) AS total
FROM devices
)x
WHERE device='apple'
GROUP BY 1 

By the way, you can rewrite this query as:

SELECT 'apple' as device, sum(device = 'apple') AS count,
       100 * sum(device = 'apple') / count(*) AS percentage
FROM devices ;

This removes the extra table scan for calculating the total and the join (which is really cheap because there is only one row in x .

Where goes before group by and fater from and join:

SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices 
CROSS JOIN (
SELECT count( * ) AS total
FROM devices
)x
WHERE device='apple'
GROUP BY 1 

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