JOIN中的MySQL条件表名称

时间:2012-04-26 10:43:06

标签: mysql tablename

我正在研究知识产权管理系统,我在数据库中有2个表 - 商标和设计。

然后我有反对这样的事情。这意味着,如果其他人有商标或设计,看起来像我们的客户,经理可以创造新的反对意见。

例如,我有3个表:

商标:

id 
name

设计

id
name

oppostion:

id
name
object_id
object_table

我不知道,反对意见与表格相关,但我应该有可能提出这样的问题:

SELECT id, name, opposition_object.name FROM opposition
LEFT JOIN (trademark|design) as opposition_object on opposition.object_id =   (trademark|design).id

首先,我考虑将表名存储为对立表的object_table列,但后来我意识到我不知道是否可以查询表名,首先,它确实是一个糟糕的设计。

但是我受到了打击,没有任何想法。那么有人有任何想法如何处理它?<​​/ p>

2 个答案:

答案 0 :(得分:3)

也许是这样的:

SELECT 
    id, 
    name, 
    COALESCE(trademark.name,design.name) AS object_name
FROM 
    opposition
    LEFT JOIN trademark 
        on opposition.object_id =   trademark.id
        AND trademark.object_table ='trademark'
    LEFT JOIN design
        on opposition.object_id =   design.id
        AND design.object_table ='design'

答案 1 :(得分:0)

SELECT opposition.id, opposition.name, trademark.name AS object_name
FROM opposition
LEFT JOIN trademark
  ON opposition.object_id = trademark.id
WHERE opposition.object_table = 'trademark'

UNION

SELECT opposition.id, opposition.name, design.name AS object_name
FROM opposition
LEFT JOIN design
  ON opposition.object_id = design.id
WHERE opposition.object_table = 'design'

这会发出两个查询:一个加入trademark表,另一个加入design。然后使用UNION将结果统一到一个结果集中。