Mysql左边连接条件列

时间:2010-05-18 08:51:46

标签: mysql join

你可以用sql查询帮我吗? 我有这个问题: 我有两张桌子

“加入”表格:Reservation_has_meal

+----------------+
| id_reservation |
| id_meal        |
| pieces         |
+----------------+

和包含数据的表格:用餐

+-------------+
| id_meal     |
| name        |
+-------------+

的示例数据
Meal:
1 | carrot   
2 | potatoe  
3 | cucumber 

Reservation_has_meal
1 | 2 | 5230
1 | 3 | 1203

如何使用id_reservation = 1获得此结果?

id_meal | id_Reservation | name      | pcs |
--------------------------------------------
1       | 1              | carrot    | null|
2       | 1              | potatoe   | 5230|
3       | 1              | cucumber  | 1203|
--------------------------------------------

id_reservation = 2的结果:

id_meal | id_Reservation | name      | pcs |
--------------------------------------------
1       | 2              | carrot    | null|
2       | 2              | potatoe   | null|
3       | 2              | cucumber  | null|
--------------------------------------------

感谢您的建议。

3 个答案:

答案 0 :(得分:2)

检查出来

表示id_reservation = 1

select ml.id_meal  as id_meal,id_Reservation,name,pcs  from  Meal as ml
left outer join 
(select IFNULL(id_Reservation,1) as  id_Reservation, pieces as pcs,id_meal from    Reservation_has_meal    where id_reservation=1) rm
on  rm.id_meal  =  ml.id_meal

表示id_reservation = 2

select ml.id_meal  as id_meal,id_Reservation,name,pcs  from  Meal as ml
left outer join 
(select IFNULL(id_Reservation,2) as  id_Reservation, pieces as pcs,id_meal from    Reservation_has_meal    where id_reservation=2) rm
on  rm.id_meal  =  ml.id_meal

即您需要将id_reservation值替换为您用于搜索的值

答案 1 :(得分:0)

我有一些解决方案,但我不想使用内部选择,如果我在表中有更多数据,则查询非常难看。

SELECT *, (SELECT pcs FROM Reservation_has_meal WHERE Reservation_has_meal.id_meal = meal.id_meal AND Reservation_has_meal.id_reservation=1) FROM meal

答案 2 :(得分:0)

您需要在id_reservation上而不是条件联接。