[英]Select from three tables
我有三個表,其中table_2
是table_1
和table_3
之間的中間(連接)
表
table_id
...
...
table_rest
rest_id
table_id
...
休息
rest_id
...
...
和查詢選擇我使用
SELECT m.table_id, table_name
FROM tables m
JOIN table_rest mr
ON m.table_id = mr.table_id
WHERE rest_id = '$rest_id'
我現在需要的是在此查詢中加入另一個表reserv
id
...
status
要檢查是否狀態為0
, 1
,或2
不顯示我任何東西,如果沒有狀態這意味着沒有記錄給我看。 換句話說,這是保留系統,我在屏幕上顯示了幾張桌子。 如果狀態為0,1,2,則表示已獲取表格。 如果未找到狀態的任何信息,則表示該表沒有記錄,可以顯示給用戶。
編輯:示例方案
tables
table_id
1
2
3
4
5
rest
rest_id
1
2
table_rest
table_id | rest_id
1 2
2 2
3 2
4 2
5 2
因此,上面的查詢將為5 tables for rest_id=2
生成5 tables for rest_id=2
為rest_id=1
生成5 tables for rest_id=2
所以現在我有另一個表
reserv
id | status
1 0
2 1
3 2
因此,在此表中,當前reserv
了3個表。 這樣做的目的是向我展示另外兩個id=4
和id=5
因為它們不在表reserv
並且沒有任何狀態。
希望現在更加清晰了。
如果提供示例數據或sqlfiddle
。 根據我的了解:這是您想要的:
select tables.table_id, rest.rest_id
from tables
left join table_rest on table_rest.table_id = tables.table_id
left join rest on rest.rest_id = table_rest.rest_id
where rest.rest_id = '$rest_id'
and tables.table_id not in (select id from reserv)
您必須從表保留指向要預訂的表,我們稱其為reserv.table_id
SELECT m.table_id, table_name
FROM tables m
JOIN table_rest mr
ON m.table_id = mr.table_id
left join reserv
on reserv.table_id = m.id
WHERE rest_id = '$rest_id'
and reserv.status is null (*note)
*請注意,根據您的需要,根據我的需要使用“是”或“不是”,首先看起來您想要!=,后來您想要的是=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.