Home >Database >Mysql Tutorial >How to Resolve the 'View's SELECT Contains a Subquery in the FROM Clause' Error in MySQL?

How to Resolve the 'View's SELECT Contains a Subquery in the FROM Clause' Error in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 22:13:13728browse

How to Resolve the

"View's SELECT Contains a Subquery in the FROM Clause": Resolving the Issue

When attempting to create a view based on two tables, credit_orders and credit_usage, the query returns an error indicating "View's SELECT contains a subquery in the FROM clause." This error occurs because the MySQL documentation explicitly prohibits the presence of subqueries in the FROM clause of a view SELECT statement.

To resolve this issue and successfully create the view, it is necessary to create separate views for each subquery. This involves creating intermediary views for both the purchased credits calculation and the credits used calculation.

For the purchased credits calculation, the following query can be used:

CREATE VIEW view_purchased_credits AS
SELECT
  client_id,
  SUM(number_of_credits) AS purchased
FROM credit_orders
GROUP BY client_id;

For the credits used calculation, the following query can be used:

CREATE VIEW view_credits_used AS
SELECT
  client_id,
  SUM(credits_used) AS used
FROM credit_usage
GROUP BY client_id;

Once these intermediary views have been created, it is possible to create the view_credit_status view by accessing the intermediary views:

CREATE VIEW view_credit_status AS
SELECT
  co.client_id,
  v1.purchased,
  v2.used
FROM credit_orders AS co
LEFT JOIN view_purchased_credits AS v1
  ON v1.client_id = co.client_id
LEFT JOIN view_credits_used AS v2
  ON v2.client_id = co.client_id
WHERE
  co.payment_status = 'Paid';

By eliminating the subquery from the FROM clause and using intermediary views, the view_credit_status view can be successfully created without triggering the error associated with subqueries in the FROM clause.

The above is the detailed content of How to Resolve the 'View's SELECT Contains a Subquery in the FROM Clause' Error in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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