Filtering MYSQL query results based on the result of an alias (AS)

Here is a MySQL query that I'm working with:

SELECT
     t1.*,
    (SELECT count(*) FROM tb_pt t2
     WHERE t2.id_provinsi = t1.id_provinsi && nama_pt LIKE '%$nama%' && status_pt = 1 ) As jumlah
FROM tb_provinsi t1
WHERE status_provinsi = 0

The above query will produce the following result:

https://i.stack.imgur.com/bR03w.png

I am facing an issue where the query returns all results regardless of whether jumlah is 0 or not. I would like to filter these results by adding 'WHERE jumlah != 0' so that the query only returns one result where jumlah is greater than 0 (id_provinsi = Prv02).

Any suggestions or ideas on how to accomplish this? Thank you.

Answer №1

The underlying issue causing your challenge is the unavailability of an alias in the SELECT statement when it's needed in the subsequent WHERE clause execution. You can address this by duplicating your alias logic within the WHERE clause, or utilize MySQL's enhanced HAVING operator which allows referencing aliases:

SELECT
     t1.*,
    (SELECT count(*) FROM tb_pt t2
     WHERE t2.id_provinsi = t1.id_provinsi AND
           nama_pt LIKE '%$nama%' AND
           status_pt = 1) AS jumlah
FROM tb_provinsi t1
WHERE status_provinsi = 0
HAVING jumlah > 0;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to retrieve a JSON record by its specific ID using Angular's AJAX functionalities?

I've been working on a function within my service that retrieves data function getSomeData() { return $http .get('/someData.json') .then(itWorked) .catch(onFail); Currently, this function returns all the records from the J ...

Is there a way to convert the structure of HTML/CSS into JSON format?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .collapsible { background-color: #004c97; color: white; cursor: pointer; padding: 18px; width: 100%; border: none; text ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

Incorporating Hive SerDe jar into SparkSQL Thrift Server

My Hive tables are linked to JSON files as their contents, requiring the use of a JSON SerDe jar (available here) in order to query them. On the machine hosting my Hadoop distribution, I can easily add the jar to Hive or Beeline CLI by executing: ADD JAR ...

Utilizing the SELECT last_insert_id method for generating distinct and sequential identifiers

After exploring various options on different platforms, I have yet to find a solution that fits my specific scenario... SITUATION: I am working with a php system that automatically creates mysql-connected templates. For the system to function properly, e ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

PHP is used to download JSON data in mobile applications

My iOS and Android app is designed to download data from a database using JSON and PHP. The process involves numerous mysql queries that retrieve information from my MySQL database. Initially, I created an array in PHP to store all the queries and would ac ...

Is there a way to toast the values of an array retrieved from a getter within my object?

My data in the format of a JSON Array looks like this and I am attempting to display the user_review_ids values - 63,59,62 using a toast message. However, instead of getting the actual values, I keep receiving what seems to be a reference to them, such as ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

The attempt to fetch the submitted data via the PHP URL was unsuccessful

I have a form and I've created a URL to fetch data. The data is being fetched properly, but when I try to access the URL, it shows {"error":"null"}. How can I retrieve the submitted value? I am having trouble displaying the web services as I attempt t ...

Strategies for managing multiple openIDs linked to a single user account

Currently, I am implementing a login system on my website similar to the one used on SO. Users have the option to log in with their Facebook, Google (Gmail openID), or Twitter accounts. This inquiry does not focus on specific oAuth or OpenID implementatio ...

How to extract JSON data enclosed within HTML tags in Android application

My issue is slightly different than what I expected when I previously asked: Parse JSON to configure android application. I am receiving a JSON object from the server, and when I view it in the browser's source code, this is how it appears: JOSON.co ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

Is there a method to automatically replace the latest or asterisk (*) symbol in package.json with a specific version number?

When managing my project library using npm's Node Packaged Modules, I encountered issues with the unconditional latest update version causing unmet dependencies errors. I attempted to change all latest versions to my current local version, utilizing ...

How can jq be used to compactly format specific fields?

Is jq the optimal solution for formatting arbitrary JSON? cat my.json | jq . is effective for pretty-printing JSON, but it can expand each field on separate lines. However, what if certain fields are repetitive, like a list of points? How can we format m ...

Nested association in Rails for rendering as JSON is a powerful feature that allows you

I have managed to solve 90% of my issue with previous questions, but I've hit a obstacle. My models include CheckIns and Person, where CheckIns are associated with People. In my controller, I currently have this code: data = CheckIn.all render json ...

Troubleshooting a 400 Bad Request Error

Upon sending a POST request to the server in my MVC application through jQuery, a 400 Bad Request is returned when a validation error occurs, as expected: HTTP/1.1 400 Bad Request Cache-Control: private Content-Type: application/json; charset=utf-8 Server ...