我需要根据查询结果在mySQL查询中添加一个条件。
SELECT
返回了IVC_Recipient
我,我想使用此数据作为条件。但这不起作用。
以下是查询:
SELECT
KDX_Id,
KDX_Name,
KDX_FirstName,
KDX_Company,
BOO_Id,
DEB_Date,
IFNULL(SUM(IVC_Sum + IVC_Taxes), 0) AS DEB_Total,
DATEDIFF('2018-07-10', DEB_Date) AS DEB_Nb_Days,
IVC_Recipient
FROM ___Debtors
JOIN ___Invoices
ON ___Invoices.IVC_Id = ___Debtors.DEB_InvoiceId
JOIN ___Bookings
ON ___Bookings.BOO_Id = ___Invoices.IVC_BookingId
IF(IVC_Recipient = 'guest') {
JOIN ___Kardex
ON ___Kardex.KDX_Id = ___Bookings.BOO_GuestId
}
IF(IVC_Recipient = 'company') {
JOIN ___Kardex
ON ___Kardex.KDX_Id = ___Bookings.BOO_CompanyId
}
请问我在这里想念什么?
谢谢。
答案 0 :(得分:1)
您可以使用CASE
表达式:
SELECT
KDX_Id,
KDX_Name,
KDX_FirstName,
KDX_Company,
BOO_Id,
DEB_Date,
IFNULL(SUM(IVC_Sum + IVC_Taxes), 0) AS DEB_Total, -- there is no GROUP BY
DATEDIFF('2018-07-10', DEB_Date) AS DEB_Nb_Days,
IVC_Recipient
FROM ___Debtors
JOIN ___Invoices
ON ___Invoices.IVC_Id = ___Debtors.DEB_InvoiceId
JOIN ___Bookings
ON ___Bookings.BOO_Id = ___Invoices.IVC_BookingId
JOIN ___Kardex
ON ___Kardex.KDX_Id = (CASE
WHEN IVC_Recipient = 'guest' THEN ___Bookings.BOO_GuestId
WHEN IVC_Recipient = 'company' THEN ___Bookings.BOO_CompanyId
END)
答案 1 :(得分:0)
在以下情况下,几乎所有“ if”都可以表示为AND:
JOIN ___Kardex
ON (IVC_Recipient = 'guest' AND ___Kardex.KDX_Id = ___Bookings.BOO_GuestId)
OR (IVC_Recipient = 'company' AND ___Kardex.KDX_Id = ___Bookings.BOO_CompanyId)
...但是根据索引使用的工作方式,有时甚至可以提高性能,使其更简单地加入并在WHERE条件下稍后对结果进行排序(尽管这是我最后的选择,“我们能否获得更多速”)。
JOIN ___Kardex
ON ___Kardex.KDX_Id IN (___Bookings.BOO_GuestId, ___Bookings.BOO_CompanyId)
WHERE (IVC_Recipient = 'guest' AND ___Kardex.KDX_Id = ___Bookings.BOO_GuestId)
OR (IVC_Recipient = 'company' AND ___Kardex.KDX_Id = ___Bookings.BOO_CompanyId)