MySQL加入IF条件 [英] MySQL JOIN with IF conditions
本文介绍了MySQL加入IF条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望通过查询simillar获得一些结果:
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,而公司有col1和col4,但你想要他们都是。
In this example, private has columns col1, col2 and col3, whilst company has col1 and col4, but you want them all.
这篇关于MySQL加入IF条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文