2

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

选择1

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

选择2

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`)

做这个的最好方式是什么?谢谢。

4

1 回答 1

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
于 2013-03-07T14:53:33.860 回答