繁体   English   中英

SQL查询FROM变量表

[英]SQL query FROM variable tables

我有4个表:一个表包含事件 ,一个表包含这些事件的服务员 ,另外两个表包含有关这些服务员的信息,可能是单身人士还是一群人。 数据库的设计看起来很公平,对吗?

然后,我需要获得参加特定活动的人员的姓名。 然后,我将使用常规联接获取活动参加者的类型及其ID 但是我还需要服务员的姓名 ,并将其存储在两个不同的表中,具体取决于服务员的类型

看看我做了什么:

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 )

可行,但不是完美的,因为它为表返回重复的行。 我想结束的是这样的事情:(除了下面的那个不起作用)

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 )

我也可以运行两个查询,并将其结果与PHP合并,但我是喜欢学习的人。

MySQL数据库顺便说一句。 谢谢你的帮助!

    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