当其中一个值是SELECT语句的结果时,如何使用COUNT(DISTINCT ...)?

时间:2018-01-13 23:38:56

标签: mysql sql

我有一个返回行的SQL语句:

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 

如果我尝试使用COUNT函数来计算行数,我会得到一个SQL数据库错误

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

如何更改SQL以使COUNT(DISTINCT...与SELECT的结果一起使用?

2 个答案:

答案 0 :(得分:1)

您的查询返回不同的行。因此,您所要做的就是计算该查询的结果:

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

答案 1 :(得分:1)

你所尝试的是不必要的复杂。简单的方法有什么问题?

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

这将为您提供不同的价值。