我有两个表:一个用于用户信息,第二个用于映射用户之间的某些关系(两个列表有两个id,从id到id关系) 我试图为他的所有用户找到特定的用户ID'关系ids(内部选择)然后通过加入一个有更多信息显示的表来获得更多关于它们的信息。
鉴于以下错误:
错误:#1064 - 您的SQL语法出错;检查与您的mySQL服务器版本对应的手动列表,以获得正确的语法,以便在附近使用#); AS i限制0,30'第6行
我的查询有什么问题?
此查询在性能方面是否合适,还是有其他方法可以做到这一点?
查询:
SELECT i.*
FROM
((SELECT uc.contactId
FROM tbl_users AS u
JOIN tbl_users_contacts AS uc ON u.Id = uc.userId
WHERE uc.userId =1) AS contacts_ids JOIN tbl_users AS u
ON contacts_ids.contactId = u.Id) AS i;
修改:已修复为:
SELECT *
FROM
((SELECT uc.contactId
FROM tbl_users AS u
JOIN tbl_users_contacts AS uc ON u.Id = uc.userId
WHERE uc.userId =1) AS contacts_ids JOIN tbl_users AS u
ON contacts_ids.contactId = u.Id);
不知道为什么最后的As我是个问题,所以我主要针对这个帖子提出问题2。
答案 0 :(得分:1)
考虑以下
mysql> create table tbl_users ( iduser int,name varchar(100),email varchar(100));
Query OK, 0 rows affected (0.10 sec)
mysql> insert into tbl_users values
-> (1,'A','a@a.com'),
-> (2,'B','b@b.com'),
-> (3,'C','c@c.com'),
-> (4,'D','d@d.com'),
-> (5,'E','e@e.com');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> create table contacts (iduser int, contactid int );
Query OK, 0 rows affected (0.14 sec)
mysql> insert into contacts values
-> (1,2),(1,3),(1,5),(2,1),(2,5),(3,1),(3,4);
mysql> select * from tbl_users ;
+--------+------+---------+
| iduser | name | email |
+--------+------+---------+
| 1 | A | a@a.com |
| 2 | B | b@b.com |
| 3 | C | c@c.com |
| 4 | D | d@d.com |
| 5 | E | e@e.com |
+--------+------+---------+
5 rows in set (0.00 sec)
mysql> select * from contacts ;
+--------+-----------+
| iduser | contactid |
+--------+-----------+
| 1 | 2 |
| 1 | 3 |
| 1 | 5 |
| 2 | 1 |
| 2 | 5 |
| 3 | 1 |
| 3 | 4 |
+--------+-----------+
7 rows in set (0.00 sec)
现在我们可以看到userid = 1有3个联系人,我们可以将它们作为
select u.* from tbl_users u
join contacts c on c.contactid = u.iduser
where c.iduser = 1 ;
输出将为
+--------+------+---------+
| iduser | name | email |
+--------+------+---------+
| 2 | B | b@b.com |
| 3 | C | c@c.com |
| 5 | E | e@e.com |
+--------+------+---------+
为了提高性能,您可以添加以下索引
alter table tbl_users add index userid_idx(iduser);
alter table contacts add index cu_idx(iduser,contactid);
根据需要将表格和列名称更改为查询。