簡體   English   中英

當值之一是SELECT語句的結果時,如何使用COUNT(DISTINCT…)?

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

我有一條返回行的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的結果一起使用?

您的查詢返回不同的行。 因此,您要做的就是計算該查詢的結果:

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

您嘗試的操作不必要地復雜。 簡單方法有什么問題?

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

這將為您提供獨特的價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM