Mysql计数列

时间:2010-05-04 11:04:31

标签: select mysql count

我有一个图库的表格,有四列,如:

foid | uid | pic1  | pic2  | pic3  | date     |
-----------------------------------------------
104  |  5  | 1.jpg | 2.jpg | 3.jpg | 2010-01-01
105  | 14  | 8.jpg |       |       | 2009-04-08
106  | 48  | x.jpg | y.jpg |       | 2010-08-09

用户画廊的Mysql查询如下:

SELECT * FROM foto WHERE uid = $id order by foid DESC

我想要做的是计算每个列出的图库中的图像数量(PIC1,PIC2,PIC3)。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:5)

我假设每个foid代表一个图库:

SELECT foid, uid, date,
       (CASE WHEN pic1 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN pic2 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN pic3 IS NULL THEN 0 ELSE 1 END
       ) AS pic_count
  FROM foto
 WHERE uid = $id
 ORDER BY foid DESC

顺便说一句,这不是构建架构的特别明智的方法。你真的应该将这些照片拆分为一个单独的表格:

foto:
foid | uid | date
-----------------------
104  |  5  | 2010-01-01
105  | 14  | 2009-04-08
106  | 48  | 2010-08-09

pic:
foid | pic
------------
104  | 1.jpg
104  | 2.jpg
104  | 3.jpg
105  | 8.jpg
106  | x.jpg
106  | y.jpg

现在,画廊可以有三个以上的图片,查询更简单:

SELECT foid, uid, date, COUNT(*)
  FROM foto
  JOIN pic USING (foid)
 WHERE uid = $id
 ORDER BY foid DESC
 GROUP BY foid, uid, date

编辑:您可以拆分现有数据库(只是猜测列类型之类的东西):

CREATE TABLE picture (foid INT, pic VARCHAR(255));

INSERT INTO picture (foid, pic)
        SELECT foid, pic1 as pic FROM foto WHERE pic IS NOT NULL
        UNION
        SELECT foid, pic2 as pic FROM foto WHERE pic IS NOT NULL
        UNION
        SELECT foid, pic3 as pic FROM foto WHERE pic IS NOT NULL
    ;

ALTER TABLE foto
    DROP COLUMN pic1,
    DROP COLUMN pic2,
    DROP COLUMN pic3
    ;

显然,在删除列时应该非常小心,并在开始之前进行备份!