MySQL conditional table name in JOIN

有些话、适合烂在心里 提交于 2020-01-15 09:32:47

问题


I'm working on intellecual property management system, where I have 2 tables in database - trademark and design.

Then I have such thing as opposition. This means, if someone else has trademark or design, that looks like our's clients one, manager can create new opposition.

For example, I have 3 tables:

trademark:

id 
name

design:

id
name

oppostion:

id
name
object_id
object_table

I don't know, to what table opposition is related, but I should have a possibility to make such kind of query:

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

First, I thought about storing table name as object_table column of opposition table, but then I realised I don't know if it will be possible to query table name and, first of all, it's defenitely a bad design.

But I got strucked here and nothing comes to my mind. So does anyone have any ideas how to handle it?


回答1:


Maybe something like this:

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'



回答2:


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'

This issues two queries: one joining the trademark table and one joining design. Then the results are unified into one result set using UNION.



来源:https://stackoverflow.com/questions/10331807/mysql-conditional-table-name-in-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!