开发者

Multiple table JOIN issue

first, you should know that i suck big time at SQL.

Here is my problem:

I have 4 tables that i need to be joinned (for usage in SphinxSearch), here is the rough structure:

Accounts

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

Category

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

Accounts_has_subcategory

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

Subcategory

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

What i want is a resultset looking like this:

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

Right my query looks like this:

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

Like said before, i suck at SQL (as soon as it involves multiple joins or stuff like that basically...). If someone could point me in the right direction or offer a solution (with basic explanation, so i can try and get that in my brain -_-), that would make my day since i've been fighting that query for a good 5h now...

Thanks.


Try this?

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;


You're almost there - you just need to fix up your syntax a little and add a group by.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜