我无法弄清楚如何获得我需要的结果。有人可以帮忙吗?
这些是我的mySql表:
restaurant menu menu_has_dishes dishes
---------- ---- --------------- ------
id (k) <-> restaurantid id (k) title
name id (k) <-> menuid price
date dishid <-> id (k)
我需要在某一天获得所有菜单及其各自的菜单,属于餐厅。任何人都可以向我展示正确的SQL查询,也许可以解释一下......?
谢谢...:)
答案 0 :(得分:2)
SELECT d.title, d.price
FROM dishes d
JOIN menu_has_dishes md ON d.id = md.dishid
JOIN menu m ON md.menu_id = m.id
WHERE m.restaurantid = [[your restaurant id goes here]]
这将为您提供如下输出:
-----------
|Fish|1.00|
|Ham |2.00|
|... |... |
-----------
所以让我们分解一下这个问题:
--Tell the database what fields you care about
SELECT d.title, d.price
--Tell it what table to start with, and give it a nickname "d"
FROM dishes d
--join to menu_has_dishes so we know what menus contain each dish
JOIN menu_has_dishes md ON d.id = md.dishid
--join to menu so we know what restaurant has each menu
JOIN menu m ON md.menu_id = m.id
--finally, tell it what restaurant to look at
WHERE m.restaurantid = [[your restaurant id goes here]]
答案 1 :(得分:1)
这将返回表格中的所有字段,对于日期中的餐厅“5”:
SELECT *
FROM restaurant r
INNER JOIN menu m ON (r.id=m.restaurantid)
INNER JOIN menu_has_dishes md ON (m.menuid=d.menuid)
INNER JOIN dishes d ON (md.dishid=d.id)
WHERE r.id = 5
AND m.date = '2011-12-07'
您可能只想获得相关信息:
SELECT r.id, r.name, m.date, d.title, d.price
答案 2 :(得分:0)
SELECT res.id, res.name,m.id,m.date FROM restaurant res
JOIN menu m ON m.restaurantid = res.id
JOIN menu_has_dishes mhd ON mhd.menuid = m.id
JOIN dishes d ON d.id = mhd.dishid
WHERE res.id = ?
答案 3 :(得分:0)
SELECT r.name, m.date, d.title, d.price
FROM
restaurant r
INNER JOIN menu m
ON r.id=m.restaurantid
INNER JOIN menu_has_dishes md
ON m.id=md.menuid
INNER JOIN dishes d
ON md.dishid=d.id
WHERE
r.id = 123 -- OR r.name = 'abc'
AND
m.date = CONVERT(date,'2011/12/06');