简体   繁体   English

SQL查询FROM变量表

[英]SQL query FROM variable tables

I have 4 tables : one with events , one with those events' attendants , and two others containing information about those attendants, might they be single persons or groups of persons. 我有4个表:一个表包含事件 ,一个表包含这些事件的服务员 ,另外两个表包含有关这些服务员的信息,可能是单身人士还是一群人。 The design of the database seems fair, right ? 数据库的设计看起来很公平,对吗?

I then need to get the name of who is going to attend a particular event. 然后,我需要获得参加特定活动的人员的姓名。 I'll then get the type of the event's attendants, and its id using a regular join. 然后,我将使用常规联接获取活动参加者的类型及其ID But i also need attendants' names , and its stored in two different tables depending on what type the attendant is. 但是我还需要服务员的姓名 ,并将其存储在两个不同的表中,具体取决于服务员的类型

Have a look at what i did : 看看我做了什么:

SELECT
    ep.type_attendant 'type',
    ep.id_attendant 'id',
    IF( ep.type_attendant = 'user', CONCAT( u.firstname, ' ', u.lastname ), g.name ) 'fullname'
FROM
    events_attendants ep,
    events e,
    users u,
    groups g
WHERE
    ep.id_event = e.id AND
    ep.id_attendant = IF( ep.type_attendant = 'user', u.id, g.id )

That works, but is not perfect since it returns duplicate rows for the table groups . 可行,但不是完美的,因为它为表返回重复的行。 What i'd like to end up with is something like that : (except the one below doesn't work) 我想结束的是这样的事情:(除了下面的那个不起作用)

SELECT
    ep.type_attendant 'type',
    ep.id_attendant 'id',
    IF( ep.type_attendant = 'user', CONCAT( u.firstname, ' ', u.lastname ), g.name ) 'fullname'
FROM
    events_attendants ep,
    events e,
    IF( ep.type_attendant = 'user', users u, groups g ) -- variable table
WHERE
    ep.id_event = e.id AND
    ep.id_attendant = IF( ep.type_attendant = 'user', u.id, g.id )

I could also run two queries, and merge their results with PHP, but i'm the kind of guy who likes to learn. 我也可以运行两个查询,并将其结果与PHP合并,但我是喜欢学习的人。

MySQL database btw. MySQL数据库顺便说一句。 Thanks for your help! 谢谢你的帮助!

    SELECT
        ep.type_attendant AS `type`,
        ep.id_attendant   AS id,
        CONCAT( u.firstname, ' ', u.lastname ) AS fullname
    FROM
        events_attendants ep
      JOIN
        events e    ON ep.id_event = e.id 
      JOIN
        users u     ON ep.id_attendant = u.id
    WHERE
        ep.type_attendant = 'user'
UNION ALL
    SELECT
        ep.type_attendant,
        ep.id_attendant,
        g.name  
    FROM
        events_attendants ep
      JOIN
        events e    ON ep.id_event = e.id 
      JOIN
        groups g    ON ep.id_attendant = g.id
    WHERE
        ep.type_attendant <> 'user'

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

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