0

这是我想要做的:我有以下表格:

User
id     name  
1      user1


Emails
id     email                           user_id
1      something@somewhere.com         1
2      something_else@somewhere.com    1

Addresses
id    address  user_id
 1    Here     1
 2    There    1

我想做的是一个 SELECT,每个用户只包含一行,不管他有多少电子邮件和地址。问题是我还需要一个地址才能看到。所以我需要我的结果看起来像这样:

name         email                address  total_emails total_addresses
user1        something@somewhere  Here     2            2

我想到了 GROUP BY,但由于我使用 COUNT 函数来获取电子邮件和地址的数量,我被迫对所有列进行 GROUP BY,因此每个组合都会得到一个结果......

我想在 SQL 中做的甚至可能吗?是否可以使用 CodeIgniter ActiveRecord?

4

2 回答 2

0

我不熟悉 sql-server 但在 mysql 中我会这样写:

SELECT t1.id AS user_id, 
       t2.email AS user_email,
       t3.address AS user_address,
       (SELECT count(*) from emails WHERE user_id = t1.id) as total_emails,
       (SELECT count(*) from emails WHERE user_id = t1.id) as total_addresses,
FROM user t1
LEFT JOIN emails t2 on t1.id = t2.user_id
LEFT JOIN addresses t3 ON t1.id = t3.user_id
GROUP BY t1.id

如果 sql server 支持子查询,它应该可以工作

于 2012-08-13T14:40:07.287 回答
0
;With user_details AS
(
SELECT
name
,_Addresses.address
,_email.email
,row_number() OVER (PARTITION BY name ORDER BY _email.id ASC) AS email_row
,COUNT(_email.email) OVER (PARTITION BY name) AS email_count
,row_number() OVER (PARTITION BY name ORDER BY _addresses.id ASC) AS address_row
,COUNT(_addresses.address) OVER (PARTITION BY name) AS address_count
FROM _user
LEFT OUTER JOIN _email on _email.user_id = _user.id
LEFT OUTER JOIN _Addresses ON _Addresses.user_id = _user.id
)
SELECT 
name
,MAX(CASE WHEN email_row = 1 THEN email END) AS email
,MAX(CASE WHEN address_row = 1 THEN address END) AS address
,MAX(email_count) as total_emails
,MAX(address_count) as total_addresses
FROM user_details
GROUP BY name
于 2012-08-13T14:52:52.133 回答