Home > Database > Mysql Tutorial > body text

Can from be followed by case in mysql?

下次还敢
Release: 2024-05-01 20:57:41
Original
998 people have browsed it

Yes, MySQL allows the use of CASE expressions in the FROM clause to select specific rows. The syntax is: SELECT ... FROM table_name WHERE AND CASE WHEN THEN THEN ELSE END AS , where

Can from be followed by case in mysql?

#MySQL FROM Can I use CASE expression later?

Answer: Yes

Detailed explanation:

MySQL allows use in the FROM clause CASE expression to select specific rows from a table. A CASE expression is essentially a conditional statement that can return different values ​​based on given conditions.

Syntax:

<code>SELECT ...
FROM table_name
WHERE <filter_condition>
AND CASE
    WHEN <condition1> THEN <value>
    WHEN <condition2> THEN <value>
    ELSE <default_value>
END AS <alias></code>
Copy after login
Where:

  • is required before applying the CASE expression conditions met.
  • and are the conditions to be evaluated.
  • is the value returned based on the condition.
  • is the default value returned if no condition is matched.
  • is the alias assigned to the result of the CASE expression.

Example:

Suppose there is a "customers" table with the following columns:

  • customer_id
  • name
  • country
We can use CASE expression to select from a specific country/ Customers by Region:

<code>SELECT *
FROM customers
WHERE country = 'United States'
AND CASE
    WHEN age > 18 THEN 'Adult'
    WHEN age <= 18 THEN 'Minor'
    ELSE 'Unknown'
END AS `age_group`;</code>
Copy after login
This query will return all customers from the United States and classify them as adults, minors, or unknown based on age.

The above is the detailed content of Can from be followed by case in mysql?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!