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
基础教程推荐
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01