从几个主键sql获取行

时间:2013-04-11 15:48:17

标签: sql rows

我有theese表:

Works
 ____________________________________________________________________
|                                                                   |
|id  user_id  cat_id  branch_id  country  budget  explanation       |
|___________________________________________________________________|

Categories
 ____________________________________________________________________
|                                                                   |
|id  category                                                       |
|___________________________________________________________________|

Categories_Branch
 ____________________________________________________________________
|                                                                   |
|id  cat_id  branch                                                 |
|___________________________________________________________________|


I want them displayed like this:
 ____________________________________________________________________
|                                                                   |
|id  country  budget  explanation  category  branch                 |
|___________________________________________________________________|

我无法让它工作,目前的SQL是:

SELECT works.id, works.country, works.budget, works.explanation, categories.category, categories_branch.branch
FROM works, categories, categories_branch
WHERE works.user_id = ".$_SESSION['customer_id']."
AND works.cat_id = categories.id
AND categories_branch.cat_id = categories.id
GROUP BY works.id

这会使分支组出错,显示错误的分支。

有谁知道如何解决这个问题?非常感谢所有帮助。

修改

这是显示我想要它如何排序的图像,问题是显示了错误的分支。

http://i.imgur.com/M7GIwlk.png

1 个答案:

答案 0 :(得分:1)

让我们从这开始,然后从那里开始:

SELECT works.id, works.country, works.budget, works.explanation, categories.category, categories_branch.branch
FROM works
INNER JOIN categories ON works.cat_id = categories.id
INNER JOIN categories_branch ON categories_branch.cat_id = categories.id
WHERE works.user_id = ".$_SESSION['customer_id']."