【问题标题】:mysql select on two different tables depending on field-valuemysql 根据字段值在两个不同的表上选择
【发布时间】:2017-06-08 14:49:13
【问题描述】:

我有以下问题,我的大脑烧坏了:)

我有两张包含个人数据的表格(一张用于客户“table_a”,一张用于有趣的人“table_b”)。 在第三个表“table_inv”中,两个表(a 和 b)中都有带有受邀人员的条目。

table_inv 有一个字段“invited_id”,其中存储了表 a 或表 b 的 id。另一个字段 'type' 具有值 'cust' 或 'interest' 以区分条目来自哪个表(a 或 b)。

现在我必须根据字段“类型”的值从 table_a / table_b 获取完整数据...

我尝试了 case 和 if 但没有结果。

我正在寻找这样的东西:

SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
FROM ext_event_invites a
CASE a.type
    WHEN 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
END CASE
WHERE a.eventid = :eventid AND a.userid = '4711' 
ORDER BY b.name_last ASC, b.name_first ASC

谁能帮帮我?

【问题讨论】:

    标签: mysql if-statement select


    【解决方案1】:

    您可以简单地加入两个表,然后有条件地从相关表中选择数据。下面给出了另一种选择。我假设'CUST' 的替代品是'CONT'(用于“联系”),所以如果是别的东西,你需要调整它......

    SELECT
        a.id, a.created, a.userid, a.type, a.inviteid,
        b.name_first, b.name_last, b.zip, b.city
    FROM
        ext_event_invites i
        LEFT JOIN 
        (
        SELECT
           'CUST' as type,
           a.name_first,
           a.name_last,
           a.zip,
           a.city
        FROM accounts a
    
        UNION ALL
    
        SELECT
           'CONT' as type,
           c.name_first,
           c.name_last,
           c.zip,
           c.city
        FROM ext_contacts c
        ) as b ON
           i.inviteid = b.id AND
           i.type = b.type
    WHERE
        a.eventid = :eventid AND a.userid = '4711' 
    ORDER BY
        b.name_last ASC,
        b.name_first ASC
    

    【讨论】:

    • @pengels。如果这对你有用,请告诉我。如果没有,请告诉我,我会尽力解决。如果是这样,请将答案标记为“已接受”以表示感谢。
    • 刚刚发现我的别名有一些拼写错误。这些现在已得到纠正。请让我知道你是如何处理这件事的。
    【解决方案2】:

    请试试这个。这应该可以。

    SELECT a.id, a.created, a.userid, a.type, a.inviteid, b.name_first, b.name_last, b.zip, b.city
    FROM ext_event_invites a
    IF a.type = 'CUST' THEN
        LEFT JOIN accounts b ON a.inviteid = b.id;
    ELSE
        LEFT JOIN ext_contacts b ON a.inviteid = b.id;
    WHERE a.eventid = :eventid AND a.userid = '4711' 
    ORDER BY b.name_last ASC, b.name_first ASC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多