简体   繁体   中英

How can you use COUNT(DISTINCT…) when one of the values is the result of a SELECT statement?

I have a SQL statement that returns rows:

SELECT DISTINCT wp_w2bw2c_event.venue_id, 
    (SELECT MIN(begin_date)     
        FROM wp_w2bw2c_event_detail 
        WHERE wp_w2bw2c_event_detail.event_id = wp_w2bw2c_event.id) 
    as begin_date, 
    wp_w2bw2c_event.id as event_id 
    FROM wp_w2bw2c_event 
    INNER JOIN wp_w2bw2c_venue 
    ON wp_w2bw2c_venue.id = wp_w2bw2c_event.venue_id 
    INNER JOIN wp_w2bw2c_event_detail 
    ON wp_w2bw2c_event_detail.event_id = wp_w2bw2c_event.id 
    WHERE wp_w2bw2c_venue.venue_name LIKE '%ironworks%' 
    OR artist_name LIKE '%ironworks%' 
    OR event_title LIKE '%ironworks%' 
    OR event_detail_title LIKE '%ironworks%' 
    ORDER BY wp_w2bw2c_event.venue_id, begin_date, event_id 

If I try and use the COUNT function to just count the number of rows, I get a SQL database error

SELECT COUNT(DISTINCT wp_w2bw2c_event.venue_id, 
    (SELECT MIN(begin_date)     
        FROM wp_w2bw2c_event_detail 
        WHERE wp_w2bw2c_event_detail.event_id = wp_w2bw2c_event.id) 
    as begin_date, 
    wp_w2bw2c_event.id as event_id) 
    FROM wp_w2bw2c_event 
    INNER JOIN wp_w2bw2c_venue 
    ON wp_w2bw2c_venue.id = wp_w2bw2c_event.venue_id 
    INNER JOIN wp_w2bw2c_event_detail 
    ON wp_w2bw2c_event_detail.event_id = wp_w2bw2c_event.id 
    WHERE wp_w2bw2c_venue.venue_name LIKE '%ironworks%' 
    OR artist_name LIKE '%ironworks%' 
    OR event_title LIKE '%ironworks%' 
    OR event_detail_title LIKE '%ironworks%' 

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as begin_date, 
    wp_w2bw2c_event.id as event_id 
    FROM wp_w2bw2c_event 
    INNE' at line 5

How can I change the SQL so that COUNT(DISTINCT... works with the result of a SELECT?

Your query returns distinct rows. So all you have to do is count the results from that query:

select count(*) from (your query) q;

What you are attempting is unnecessarily complicated. What is wrong with the simple way?

select venueId
, min(begin_date) minBeginDate
from etc
where whatever
group by venueId

This will give you distinct values.

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