JOIN的一些說明
SQL JOIN
left join/right join/inner join的用法比較
example:
goals table
id | name |
1 | abc |
2 | def |
tasks table
id | name | goals_id |
1 | task1 | 1 |
2 | task2 | 1 |
3 | task3 | 2 |
想用goal name 做查詢時
@tasks = Task.find(:all,
:joins => "inner join goals on tasks.goal_id = goals.id",
:conditions => "goals.name = 'abc' ",
:select=>"tasks.id, tasks.name, task.goals_id")
如果沒有用:select 會find出
id | name | goals_id | id | name |
1 | task1 | 1 | 1 | abc |
2 | task2 | 1 | 1 | abc |
這樣如果直接查@tasks.id 都是查到後面的 goal的id 都是1
所以要用:select 去取出tasks table的部份
這樣便可以查出
id | name | goals_id |
1 | task1 | 1 |
2 | task2 | 1 |
沒有留言:
張貼留言