0

I have an address book referred to as contacts. To help organize contacts I have groups (e.g. family, friends, work). I want to pull say, 4 or 10 examples of contacts to display for each group. This is intended for the group index page where all groups are listed though is not intended to have a full list of contacts per group (that is for the dedicated group page only).

Groups Table and Columns

email_groups

id, id_user, name

Contacts Table and Columns

email_contacts

id, id_group, id_user, name

I've been working on this but am getting a wrong column name for c1.

SELECT 
eg.id, 
eg.name, 
(SELECT c1.name FROM email_contacts AS c1 WHERE id_user='1' LIMIT 0,1) AS contact_1, 
(SELECT c2.name FROM email_contacts AS c1 WHERE id_user='1' LIMIT 1,1) AS contact_2, 
(SELECT c3.name FROM email_contacts AS c3 WHERE id_user='1' LIMIT 2,1) AS contact_3, 
(SELECT c4.name FROM email_contacts AS c4 WHERE id_user='1' LIMIT 3,1) AS contact_4 
FROM email_groups AS eg 
INNER JOIN email_contacts AS ec on ec.id=eg.id_group
4

1 回答 1

0

您在子查询中提供了两次别名C1,我想这将是C2第二个子查询,您正在尝试选择c2.name,但您已将别名提供为c1 SELECT c2.name FROM email_contacts AS c1

SELECT 
eg.id, 
eg.name, 
(SELECT c1.name FROM email_contacts AS c1 WHERE id_user='1' LIMIT 0,1) AS contact_1, 
(SELECT c2.name FROM email_contacts AS c2 WHERE id_user='1' LIMIT 1,1) AS contact_2, 
(SELECT c3.name FROM email_contacts AS c3 WHERE id_user='1' LIMIT 2,1) AS contact_3, 
(SELECT c4.name FROM email_contacts AS c4 WHERE id_user='1' LIMIT 3,1) AS contact_4 
FROM email_groups AS eg 
INNER JOIN email_contacts AS ec on ec.id=eg.id_group
于 2013-09-21T14:36:37.000 回答