多表JOIN问题

时间:2011-08-24 18:24:10

标签: mysql sql join

首先,你应该知道我在SQL上花了很多时间。

这是我的问题:

我有4个表需要加入(用于SphinxSearch),这里是粗略的结构:

帐户

Id Name Category
----------------
1  Test 1
2  Foo  2
3  Bar  1

分类

Id Name
-------
1  Restaurants
2  Store

Accounts_has_subcategory

account_id subcat_id
--------------------
1          1
1          3
2          2

子类别

Id Name
-------
1  Chinese
2  Sportswear
3  Delivery

我想要的是一个看起来像这样的结果集:

accounts.id | accounts.name | category_name | subcategories
-----------------------------------------------------------
1             Test            Restaurants     Chinese, Delivery
2             Foo             Store           Sportswear

我的查询是这样的:

SELECT a.id, a.name, c.name as category, group_concat(subcat.name) as subcategories
FROM accounts AS a
JOIN (account_has_subcategory AS ahs, subcategory AS subcat)
ON (a.id = ahs.account_id AND ahs.subcat_id = subcat.id),
accounts AS a2
JOIN category AS c
ON a2.category = c.id

就像之前说过的那样,我对SQL很感兴趣(一旦它涉及多个连接或类似的东西......)。如果有人可以指出我正确的方向或提供一个解决方案(有基本的解释,所以我可以尝试在我的大脑中得到它-_-),这将使我的一天,因为我一直在争取一个良好的5h查询现在...

感谢。

2 个答案:

答案 0 :(得分:2)

试试这个?

SELECT a.id, a.name, 
       c.name as category, 
       group_concat(subcat.name) as subcategories
FROM accounts AS a
INNER JOIN account_has_subcategory AS ahs ON a.id = ahs.account_id
INNER JOIN subcategory AS subcat ON subcat.id = ahs.subcat_id
INNER JOIN category AS c ON a.category = c.id
GROUP BY a.id, a.name, c.name
ORDER BY a.id;

答案 1 :(得分:2)

你几乎就在那里 - 你需要稍微修改一下你的语法并添加一个组。

select a.id, a.name, c.name as category, group_concat(subcat.name) as subcategories
from accounts as a
inner join category as c on a.category = c.id
inner join accounts_has_subcategory as ahs on a.id = ahs.account_id
inner join subcategory as subcat on ahs.subcat_id = subcat.id
group by a.id, a.name, c.name