我想从表中获取问题,但是我有一个问题,我将用户名存储为外键,现在我想加入到表中,无论是客户还是雇员,即我想获取用户名,我必须加入如果客户提出问题,则发送至客户表;如果员工提出问题,则发送至客户表

table question
id question askedby
1  Hello     user
2  What is?  user


table login
id username password role
1  john       pp123  emp
2  haris      xx589  cus

table customer
id fname  lname username
1  Johnny  Kip    John

table employee
id fname  lname username backgroud dutytime
1  Harisi  Ahmed  Haris    xyz       19:00


我想在一个查询中完成所有这些操作,我只能将问题加入登录表,现在我必须查看角色是否为“ emp”,然后与客户一起加入,否则与雇员一起加入。

任何帮助将不胜感激。

谢谢

最佳答案

对于这种任务,我可以有很多解决方案。这里还有三个。

我必须承认,我不确定它们的性能。您必须自己测试:)

SELECT
     a.*
    ,IF(c.id IS NULL, e.fname, c.fname) AS fname
    ,IF(c.id IS NULL, e.lname, c.lname) AS lname
FROM
    login a
    LEFT JOIN customer c ON c.username=a.username AND a.role='cus'
    LEFT JOIN employee e ON e.username=a.username AND a.role='emp'
;


要么

SELECT
     a.*
    ,COALESCE(
        (SELECT c.fname FROM customer c WHERE c.username=a.username AND a.role='emp'),
        (SELECT e.fname FROM employee e WHERE e.username=a.username AND a.role='cus')
    ) AS fname
    ,COALESCE(
        (SELECT c.lname FROM customer c WHERE c.username=a.username AND a.role='emp'),
        (SELECT e.lname FROM employee e WHERE e.username=a.username AND a.role='cus')
    ) AS lname
FROM
    login a
;


也许更好

SELECT
     a.*
    ,IF(a.role='cus',
        (SELECT c.fname FROM customer c WHERE c.username=a.username),
        (SELECT e.fname FROM employee e WHERE e.username=a.username)
    ) AS fname
    ,IF(a.role='cus',
        (SELECT c.lname FROM customer c WHERE c.username=a.username),
        (SELECT e.lname FROM employee e WHERE e.username=a.username)
    ) AS lname
FROM
    login a
;


我个人认为(未经测试),首先我的SELECT应该比其他的更好,但是MySQL有时喜欢(更好的性能)子选择比联接更好。

关于mysql - 如果在Mysql中加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23984545/

10-15 20:46