gpt4 book ai didi

mysql - SQL 查询 FROM 变量表

转载 作者:行者123 更新时间:2023-11-29 03:11:38 25 4
gpt4 key购买 nike

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

然后我需要获得将要参加特定事件的人员的姓名。然后,我将使用常规联接获取事件参加者的 type 及其 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 )

这行得通,但并不完美,因为它返回表 groups 的重复行。我想要的结果是这样的:(除了下面那个不起作用)

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'

关于mysql - SQL 查询 FROM 变量表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7295876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com