我有一组三张表:
Dining_Tables; +--------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+-------+ | dining_table | int(11) | NO | PRI | NULL | | | bus_boy | varchar(35) | NO | | NULL | | | waiter | varchar(35) | NO | | NULL | | | server | varchar(35) | NO | | NULL | | +--------------------+--------------+------+-----+---------+-------+ Poker_Tables; +--------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+-------+ | poker_table | int(11) | NO | PRI | NULL | | | dealer | varchar(35) | NO | | NULL | | | pit_boss | varchar(35) | NO | | NULL | | +--------------------+--------------+------+-----+---------+-------+ Computer_Tables; +--------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+-------+ | computer_table | int(11) | NO | PRI | NULL | | | programmer | varchar(35) | NO | | NULL | | +--------------------+--------------+------+-----+---------+-------+
这些行中的每一行都有与之关联的全局唯一表 ID:(dining_table
、poker_table
、computer_table
)
其他列存储完成滚动的人的名字/姓氏。
在我的模型中,一个人可以做多件事。例如,Joe Smith 可能同时作为程序员坐在 computer_table
旁,作为荷官坐在 poker_table
旁,并在 dining_table
旁等待作为服务员。
我的问题是:
我想要一个允许我检索给定人员的所有 table_ids
的查询。具体来说,查询将返回 Joe Smith 当前所在的 table_ids
列表。
我可以按照这些思路做一些事情:
select dining_table from Dining_Tables where bus_boy = "Joe Smith" or waiter = "Joe Smith" or server = "Joe Smith"; select poker_table from Poker_Tables where dealer = "Joe Smith" or pit_boss = "Joe Smith"; select computer_table from Computer_Tables where programmer = "Joe Smith";
但是,这是三个独立的查询,我真的希望尽可能避免这样做。我可以使用联接在一个查询中完成吗?
最佳答案
您的数据模型不是最优的。考虑:
Person PersonRole Role Table ------ ---------- ---- ----- Id* PersonId* Id* Id* Name RoleId* Name Name TableId
That being said...
select dining_table from Dining_Tables where
bus_boy = "Joe Smith" or
waiter = "Joe Smith" or
server = "Joe Smith"
union
select poker_table from Poker_Tables where
dealer = "Joe Smith" or
pit_boss = "Joe Smith"
union
select computer_table from Computer_Tables where
programmer = "Joe Smith"
关于MySQL:跨多个表的多列连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/786759/