MySql获取关联表中所有记录的状态

时间:2013-11-13 10:23:49

标签: mysql sql

给出以下数据库:

CREATE TABLE album ( id int );

INSERT INTO album (id) VALUES
(1),
(2),
(3),
(4);

CREATE TABLE icon_album ( albumID int, current int );

INSERT INTO icon_album (albumID, current) VALUES
(1, 1),
(1, 1),

(2, 1),
(2, 0),

(3, 0),
(3, 0);

我想得到以下结果

albums:  id   status
         1      1
         2      0
         3      0
         4      0

什么是MySql查询才能给我正确的结果?

P.S。 1:这是我对这个问题的第二个问题。这个first question没有产生可行的解决方案

2 个答案:

答案 0 :(得分:1)

这是你要找的吗?

SELECT a.id, IF(i.current IS NULL, 0, current) AS status
FROM album a LEFT JOIN
(
    SELECT albumID, MIN(current) AS current
    FROM icon_album
    GROUP BY albumID
) i ON a.id = i.albumID

答案 1 :(得分:0)

尝试这样

"SELECT albumID AS id, if(SUM(current)>1,1,0) AS status FROM icon_album GROUP BY albumID"