Hello People我有两张桌子......
Users
- id (
- username
sample data (1:alex,2:rocky,3:kothi)
linked_table
- from_id
- to_id
sample data (1:2,1:3)
我想从linked_table.i中获取并显示from_name和To_name尝试加入并选择,但它只从from_name
获取 $Get_Linked_name = \DB::table('linked_table')
->join('users','linked_table.from_id','=','users.Id')
->where(array('linked_table.from_id'=>1))
->select()->get();
'linked_table.from_id'=>1
已链接到2,3
现在我想要获取username
2,3
我知道可以使用另一个空数组和foreach loop
完成但是还有其他更好的选择吗?
updated: From_name and To_name are nothing but username of users table
答案 0 :(得分:0)
使用UNION
SELECT u.id, u.username
FROM Users u, JOIN linked_table lt
ON u.id = lt.from_id
WHERE lt.from_id = 1
UNION
SELECT u.id, u.username
FROM Users u, JOIN linked_table lt
ON u.id = lt.to_id
WHERE lt.from_id = 1
答案 1 :(得分:0)
您可以尝试此查询:
SELECT from.username as From_name, to.username as To_name
FROM Users from, Users to, linked_table lt
WHERE from.id = lt.from_id
AND to.id = lt.to_id
AND from.id = 1