我希望通过类似于以下的查询获得一些结果:
SELECT
* FROM
users LEFT JOIN
IF (users.type = '1', 'private','company') AS details ON
users.id = details.user_id WHERE
users.id = 1
有什么想法吗?
答案 0 :(得分:24)
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
我认为这就是你要做的事,不是吗?
正如您现在所说的列数不同,您需要指定列,例如
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,但你想要它们全部。
答案 1 :(得分:17)
我确信这已经解决了,但对于有类似问题的人来说。
您还可以尝试多个左连接来获取所有数据
SELECT *, IF (users.type = 1, p.name, c.name) AS name FROM users
LEFT JOIN private AS p ON (users.type = 1 AND users.id = p.user_id)
LEFT JOIN company AS c ON (users.type != 1 AND users.id = c.user_id)
答案 2 :(得分:6)
SELECT
users.*,
details.info,
CASE users.type WHEN '1' THEN 'private' ELSE 'company' END AS user_type
FROM
users
INNER JOIN (
SELECT user_id, info FROM private
UNION
SELECT user_id, info FROM company
) AS details ON details.user_id = users.id
编辑:答案的原始版本(问题被误解):
SELECT
*,
CASE type WHEN '1' THEN 'private' ELSE 'company' END AS details
FROM
users
WHERE
users.id = 1
答案 3 :(得分:0)
在这里,我正在共享Magento2 SQL查询中的if else条件,以获取客户登录的报告订单明细,而不是同时登录,您只是根据情况增强了查询。
SELECT so.increment_id as ID,sog.customer_id as Customer_Id, sog.customer_name as Customer_Name, sog.customer_email as Customer_Email,CASE sog.customer_group WHEN '1' THEN 'Custome Login' ELSE 'Not Login' END as Customer_Group, sog.grand_total as Grand_Total,sog.subtotal as Subtotal, sog.billing_name as Billing_Name,sog.billing_address as Billing_Address,sog.shipping_address as shipping_address,so.shipping_description as Shipping_Information, so.status as Status,so.cancel_order_username as Canceled_BY,so.cancel_order_currenttime as Cancellation_Time, so.cancel_order_comment as Cancellation_Reason from sales_order so LEFT JOIN sales_order_grid as sog ON sog.increment_id=so.increment_id where so.cancel_order_currenttime >= Date('2018-10-01') AND so.cancel_order_currenttime <= Date('2018-12-05')
Here we have created some alias according to the situation:-
so->sales_order table,
sog->sales_order_grid,
and we are using the if/else condition in the customer group because we know that, "0" is used for the Guest user,
"1" is used for the login user and both are used for the customer group:-
我希望这个建议能帮助您解决困惑,如果您在理解本文时遇到任何问题,请告诉我。