LoginSignup
4
5

More than 5 years have passed since last update.

COUNT句内でもDISTINCTキーワードは使える

Last updated at Posted at 2015-03-25

COUNT内でもDISTINCTは使える。知らなかった。MySQL以外でも使えるのかはわからない。諸事情からサブクエリを使いたくない場合に活躍するかもしれない。

SELECT
  s.id AS `店舗ID`
  COUNT(DISTINCT i.id) AS '店舗画像数'
  COUNT(DISTINCT m.id) AS '店員数'
  COUNT(DISTINCT CONCAT(m.id, (m.isWorking = 1 OR null))) AS '勤務中店員数'
FROM 
  shop AS s
LEFT JOIN
  image AS i
ON
  i.shopId = s.id
LEFT JOIN
  member AS m
ON
  m.shopId = s.id
GROUP BY
  s.id

MySQL 5.5 Reference Manual :: 12.17.1 GROUP BY (Aggregate) Functions

COUNT(DISTINCT expr,[expr...])
Returns a count of the number of rows with different non-NULL expr values.

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5