简体   繁体   English

从三个表中选择

[英]Select from three tables

I have three tables where table_2 is the middle(connected) between table_1 and table_3 我有三个表,其中table_2table_1table_3之间的中间(连接)

tables

table_id
...
...

table_rest table_rest

rest_id
table_id
...

rest 休息

rest_id
...
...

And the query to select I use 和查询选择我使用

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'

What I need now is to join in this query another table reserv 我现在需要的是在此查询中加入另一个表reserv

id
...
status

To check if status is 0 , 1 ,or 2 to not show me anything if there is no status this mean there is no record to show me. 要检查是否状态为01 ,或2不显示我任何东西,如果没有状态这意味着没有记录给我看。 In other words this is resserved system where I show on screen few tables. 换句话说,这是保留系统,我在屏幕上显示了几张桌子。 If status is 0,1,2 thats mean the table is taken. 如果状态为0,1,2,则表示已获取表格。 If nothing is found for status this mean that there is no record for table and can be shown to user. 如果未找到状态的任何信息,则表示该表没有记录,可以显示给用户。

EDIT: Sample scenario 编辑:示例方案

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

So the query that is above will generate 5 tables for rest_id=2 and none for rest_id=1 So now I have another table 因此,上面的查询将为5 tables for rest_id=2生成5 tables for rest_id=2rest_id=1生成5 tables for rest_id=2所以现在我有另一个表

reserv

id | status
 1     0
 2     1
 3     2

So in this table reserv currently are saved 3 tables. 因此,在此表中,当前reserv了3个表。 The idea is to show me other two whit id=4 and id=5 because they are not in table reserv and don't have any status. 这样做的目的是向我展示另外两个id=4id=5因为它们不在表reserv并且没有任何状态。

Hope is a little bit more clear now. 希望现在更加清晰了。

It's better if you provide sample data or sqlfiddle . 如果提供示例数据或sqlfiddle Based on what I realize: Is this what you want: 根据我的了解:这是您想要的:

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)

You have to point from table reserv to which table is beign booked, let's call it reserv.table_id 您必须从表保留指向要预订的表,我们称其为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)

*note use 'is' or 'is not' depending of your needs, as far as I read, first seems that you want !=, later that what you want is = *请注意,根据您的需要,根据我的需要使用“是”或“不是”,首先看起来您想要!=,后来您想要的是=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM