来自数据规范化表的MySQL查询

时间:2017-02-06 19:14:43

标签: mysql

我有三张桌子:

用户

user_id    username
---------------------
1        |  mrzander  
2        |  foo
3        |  bar
---------------------

利益

interest_id    interest
------------------------
1            |  cars
2            |  power tools
3            |  shaving
4            |  phones
5            |  computers
------------------------

user_interests

id    uid    iid
-----------------
1   |  1   |  2
2   |  1   |  4
3   |  2   |  3
4   |  1   |  5
-----------------

基本上,我有一个用户表,一个兴趣表和一个表格,显示用户有什么兴趣。如果我知道我想从哪个用户ID获得兴趣,那么什么查询会给我所有特定用户的兴趣?

在这个例子中,什么查询会返回一个名为“Interests”的表,它告诉我user_id = 1喜欢电动工具,手机和电脑?

2 个答案:

答案 0 :(得分:1)

如果您希望结果在同一行,则应使用join和group concat

select c.username, group_concat( b.interst)
from user_interest as a
left join interest as b on a.iid = b.interest_id
left join users as c. on c.user_id = a.uid
where  c.user_id = 1
group by c.username

或者如果您需要在不同行上生成结果,请仅加入

select c.username,  b.interst
from user_interest as a
left join interest as b on a.iid = b.interest_id
left join users as c. on c.user_id = a.uid
where  c.user_id = 1

答案 1 :(得分:0)

只需加入两个表格。

select i.*
from interests i
join user_interests u
on u.iid = i.interest_id
where i.uid = 1;