How can MySQL display different results based on different conditions?
To display different results based on different conditions, you can use the CASE statement in MySQL. Similar to the switch statement in programming languages, the CASE statement allows you to execute different operations based on different conditions.
Here is a simple example: Let’s say we have a table of students, including their names and grades, and we want to display different levels based on their grades.
SELECT
name,
score,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
ELSE 'D'
END AS grade
FROM students;
In this example, students with a score of 90 or above receive an ‘A’, those with a score of 80 or above receive a ‘B’, those with a score of 70 or above receive a ‘C’, otherwise they receive a ‘D’.
You can use more conditions to display different results based on actual situations. The CASE statement can be nested and used with other SQL statements to meet your needs.