MySQL JOIN with IF conditions(带有 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 IF 条件的 MySQL JOIN
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01