I\'m having trouble understanding how MySQL optimizes SELECT statements.
Say I have 3 tables: orders, customers, and products. The primary key for the orders table is order_number, keep that in mind. I want to select all the information about a certain order number. To make things easier on whoever enters the order number, I want to use string expressions to get as many order #\'s that might enter what the user enters. Here is an exaple sql statement:
SELECT o.order_number, c.customer_name, p.product_name
FROM orders AS o, customers AS c, products AS p
WHERE o.order_number LIKE \'%$whatever%\'
AND c.customer_id=o.customer_id
AND p.product_id=o.product_id
the statement above takes ages to execute when customers gets large. Why? because MySQL grabs all of the rows from customers, then matches the orders and products to those rows. This behavior does not happen if I change
\"WHERE o.order_number LIKE \'%$whatever%\'\"
to
\"WHERE o.order_number=\'$whatever\'\"
if you make that change, MySQL sees o.order_number is primary, so will only return 1 possible row, and then grabs the results fast. So why does it not do the same when using LIKE? I think MySQL is assuming if it grabs the matching order numbers, it will take longer, but unless someone enters a single digit order number, this will not be the case. Any suggestions/opinions?