I have a small database for a retail scenario, within this I have a field called "Dispatched" which is a bool to indicate if the item has been dispatched yet. This is of course as 1 and 0, I have attempted a simple CASE WHEN to make 1 display as Yes and 0 as No.

My full query is:

SELECT 
orders.OrdersID, 
stock.ItemName, 
basket.Quantity, 
customer.FirstName, 
customer.LastName, 
address.AddressLine1, 
address.AddressLine2, 
address.TownOrCity, 
address.Postcode, 
address.Country, 
CASE WHEN basket.Dispatched = 1 THEN 'Yes' ELSE 'No' END AS basket.Dispatched 
FROM orders
JOIN OrdersBasketJoin ON orders.OrdersID = OrdersBasketJoin.OrdersID
LEFT JOIN basket ON OrdersBasketJoin.BasketID = basket.BasketID
JOIN customer ON orders.CustomerID = customer.CustomerID
JOIN address ON orders.DeliveryAddress = address.AddressID
JOIN stock ON basket.StockID = stock.StockID
ORDER BY  `customer`.`CustomerID` ASC
LIMIT 0 , 30

The query works fine without the CASE WHEN, and will display the 1s and 0s when Dispatched is selected normally, as well as WHERE working fine when referencing Dispatched.

However when I try adding

CASE WHEN basket.Dispatched = 1 THEN 'Yes' ELSE 'No' END AS basket.Dispatched

I get the error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.Dispatched FROM orders JOIN OrdersBasketJoin ON orders.OrdersID = Ord' at line 12

From what I've researched this is pretty much as simple of a CASE WHEN you can do, and the syntax is correct I believe.

Not sure if its just a visual bug, but "END" in the CASE doesn't light up like it is known to be a function, whereas JOIN, ON, LEFT etc all light up, no matter where END doesn't.

Any and all help is much appreciated -Tom

有帮助吗?

解决方案

You are missing with , after address.Country therefore you are getting syntax error try this one

SELECT 
orders.OrdersID, 
stock.ItemName, 
basket.Quantity, 
customer.FirstName, 
customer.LastName, 
address.AddressLine1, 
address.AddressLine2, 
address.TownOrCity, 
address.Postcode, 
address.Country, 
(CASE WHEN basket.Dispatched = 1 THEN 'Yes' ELSE 'No' END) AS `basket.Dispatched` 
FROM orders
JOIN OrdersBasketJoin ON orders.OrdersID = OrdersBasketJoin.OrdersID
LEFT JOIN basket ON OrdersBasketJoin.BasketID = basket.BasketID
JOIN customer ON orders.CustomerID = customer.CustomerID
JOIN address ON orders.DeliveryAddress = address.AddressID
JOIN stock ON basket.StockID = stock.StockID
ORDER BY  `customer`.`CustomerID` ASC
LIMIT 0 , 30

其他提示

Put backticks:

AS `basket.Dispatched` 
CASE WHEN basket.Dispatched = 1 THEN 'Yes' ELSE 'No' END AS 'basket.Dispatched'

You are missing single quotes before and after the aliase name.

I have tried this in my DEV machine without the single quote and have the same error.

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top