带有 IF 条件的 MySQL JOIN [英] MySQL JOIN with IF conditions

查看:118
本文介绍了带有 IF 条件的 MySQL JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过查询获得一些结果,类似于:

I want to get some results via query simillar to:

SELECT 
    * FROM
    users LEFT JOIN
    IF (users.type = '1', 'private','company') AS details ON
    users.id = details.user_id WHERE
    users.id = 1

有什么想法吗?

推荐答案

SELECT * FROM users 
LEFT JOIN private AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type = 1

UNION

SELECT * FROM users 
LEFT JOIN company AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type != 1

我认为这就是你想要做的,不是吗?

I think that is what you are trying to do, isn't it?

正如您现在所说的列数不同,您需要指定列,例如

As you have now said that the number of columns differs, you would need to specify the columns, e.g.

SELECT 'private' AS detailType, users.*, col1, col2, col3, '' FROM users 
LEFT JOIN private AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type = 1

UNION

SELECT 'company', users.*, col1, '', '', col4  FROM users 
LEFT JOIN company AS details ON users.id = details.user_id 
WHERE users.id = 1 AND users.type != 1

在这个例子中,private 有 col1、col2 和 col3 列,而 company 有 col1 和 col4,但你想要它们全部.

In this example, private has columns col1, col2 and col3, whilst company has col1 and col4, but you want them all.

这篇关于带有 IF 条件的 MySQL JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆