有人能告诉我如何从两张桌子中选择?我有这些表。
第一个叫做:动物
有:
id owner_name animal_name
1 ludvik120 Larry
2 marekk50 Pat
3 ludvik120 Riki
第二个叫做: Animal_food
有:
id owner_name food
1 marekk50 carrot
2 ludvik120 apple
3 ludvik120 orange
我想要实现的是输出:
Pat - carrot
,
Larry - apple
,
Riki - orange
如您所见,“owner_name”列相同。有可能这样做吗?
答案 0 :(得分:1)
试试这个
SELECT Animals.animal_name, Animal_food.food
FROM Animals
LEFT JOIN Animal_food
ON Animals.owner_name=Animal_food.owner_name;
连接两个字段
SELECT COALESCE(Animals.animal_name, ' - ') || COALESCE(Animal_food.food, ' - ')
FROM Animals
LEFT JOIN Animal_food
ON Animals.owner_name=Animal_food.owner_name;
答案 1 :(得分:0)
是的,确实如此。 SQL连接用于组合来自两个或多个表的行。
不同类型的JOIN:
一般语法是:SELECT column-names FROM table-name1 JOIN table-name2 ON column-name1 = column-name2 条件
程序员需要根据他/她在程序中的要求找出哪一个适合他/她。
答案 2 :(得分:0)
I recomend to use Ids like this:
Animals
AnimalId owner_name animal_name
1 ludvik120 Larry
2 marekk50 Pat
3 ludvik120 Riki
Animal_food
Animal_foodId owner_name food
1 marekk50 carrot
2 ludvik120 apple
3 ludvik120 orange
I think you need a third table to join and show the information as you need.
关系
RelationId AnimalId Animal_foodId
1 2 1
2 1 2
3 3 3
查询是:
Select A.animal_name, F.food
from Relation R
inner join Animals A on R.AnimalId = A.AnimalId
inner join Animal_food F on R.Animal_foodId = F.Animal_foodId
好看。