选择3个包含计数和连接的表

时间:2013-03-07 14:50:33

标签: mysql sql select join

我有3个表tb1,users,users_credits。 我的目标是将两个select(sel1,sel2)组合成一个视图 在sel2中显示0,其中没有行(左连接?)

SEL1

SELECT 
users.userid, 
users.datareg,
users_credits.credits,
FROM 
users,
users_credits,
WHERE
users.userid = users_credits.userid

SEL2

SELECT COUNT(*) FROM tb1 where tb1.id_user = users.userid

表格结构

tb1
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` decimal(11,0) NOT NULL,
`datains` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)

用户

`userid` int(4) unsigned NOT NULL AUTO_INCREMENT,
`datareg` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`userid`)

users_credits

`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`credits` decimal(5,0) NOT NULL,
`data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)

最好的方法是什么? 感谢。

1 个答案:

答案 0 :(得分:1)

SELECT  users.userid, 
        users.datareg,
        users_credits.credits,
        COALESCE(c.totalCount,0) totalCount
FROM    users
        LEFT JOIN users_credits
            ON users.userid = users_credits.userid
        LEFT JOIN
        (
            SELECT  id_user, COUNT(*) totalCount 
            FROM    tb1 
            GROUP   BY id_user
        ) c ON c.id_user = users.userid

要进一步了解联接,请访问以下链接:

更新1

SELECT  users.userid, 
        users.datareg,
        users_credits.credits,
        COALESCE(c.totalCount,0) totalCount,
        c.max_datains
FROM    users
        LEFT JOIN users_credits
            ON users.userid = users_credits.userid
        LEFT JOIN
        (
            SELECT  id_user, MAX(datains) max_datains, COUNT(*) totalCount 
            FROM    tb1 
            GROUP   BY id_user
        ) c ON c.id_user = users.userid

更新2

您需要为此创建两个视图:

第一视图:

CREATE VIEW tbl1View
AS
SELECT  id_user, MAX(datains) max_datains, COUNT(*) totalCount 
FROM    tb1 
GROUP   BY id_user

第二视图

CREATE VIEW FullView
AS
SELECT  users.userid, 
        users.datareg,
        users_credits.credits,
        COALESCE(c.totalCount,0) totalCount,
        c.max_datains
FROM    users
        LEFT JOIN users_credits
            ON users.userid = users_credits.userid
        LEFT JOIN tbl1View c ON c.id_user = users.userid