如果在Mysql中加入其他

时间:2014-06-01 21:13:59

标签: mysql join

我想从表中获取问题,但我有一个问题,我将用户名存储为外键,现在我想加入该表,无论是客户还是员工,即我想获取用户名,我会如果员工要求客户或员工表询问该问题,则必须加入客户表

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"然后加入客户,否则加入员工。

任何帮助将不胜感激。

由于

3 个答案:

答案 0 :(得分:1)

我可以为这项任务提供很多解决方案。还有三个。

我必须承认,我不确定每个人的表现。你必须自己测试一下:)

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有时喜欢(更好的性能)子选择比连接更好。

答案 1 :(得分:0)

一种令人费解的方法是使用UNION ALL,如

select *
from login a
join (
  select 'cus' role, username
  from customer
  union all
  select 'emp' role, username
  from employee) b on a.role = b.role and a.username = b.username;

绝对没有效率:D

答案 2 :(得分:0)

如果您可以保证客户和员工之间的用户名是唯一的,那么您可以执行以下操作(如果他们不能获得可以使用DISTINCT关键字删除的重复行,但这有点差):

Select *
From Question q
Left join Customer c on c.username = q.askedby
Left join employee e on e.username = q.askedby