Mysql : last five records if having same value - php

I searched a lot and tried many queries but not getting satisfied answer. So like to ask.
I am looking for last 5 records from mysql table if having same value otherwise not.
Something like if col_n is having same value x from last 5 records then count otherwise not. But I am not able to figure out how to write query for this ?
SELECT count(col_n)
from track if(last five col_n = 'ok')
WHERE col_a = 'value1' AND col_b = 'value2'
enter mysql table records

Please try this:
SELECT p.*
FROM
( SELECT *
FROM demo ORDER by id DESC
LIMIT 5
) AS p
JOIN
( SELECT COUNT(*) AS cnt
FROM
( SELECT 1
FROM demo
LIMIT 5
) AS tmp
) AS c
ON c.cnt = 5 WHERE p.name='x'

Related

count results different tables single query mysql php

I have the user id_user=5 who has posts in three different tables
questions (id_post | id_user ...) (7 posts)
marketplace (id_post | id_user ...) (9 posts)
jobs (id_post | id_user ...) (3 posts)
So I want to count, using a single query, the number of posts he has in each table
This is what I have so far...but it doesnt seems to work
(SELECT
COUNT(p.*) as count_questions
FROM $table_questions as p
WHERE p.id_user = :id_user1
)
UNION
(
SELECT
COUNT(m.*) as count_marketplace
FROM $table_marketplace as m
WHERE m.id_user = :id_user2
)
UNION
(SELECT
COUNT(e.*) as count_jobs
FROM $table_jobs as e
WHERE e.id_user = :id_user3
)
what am doing wrong?
I was expecting to retrieve in php like this
$count_questions = $result["count_questions"];
but it doesnt seems to work
SELECT COUNT(id_user) as counter
FROM $table_questions WHERE id_user = :id_user1
UNION
SELECT COUNT(id_user) as counter
FROM $table_marketplace WHERE id_user = :id_user2
UNION
SELECT COUNT(id_user) as counter
FROM $table_jobs WHERE id_user = :id_user3
Will return 3 rows each with the count, you have to give all the counts the same alias.
If you want to maybe identfy each result row specifically add another column as an identifier
SELECT 'Questions' as what, COUNT(id_user) as counter
FROM $table_questions WHERE id_user = :id_user1
UNION
SELECT 'Marketplace' as what, COUNT(id_user) as counter
FROM $table_marketplace WHERE id_user = :id_user2
UNION
SELECT 'Jobs' as what, COUNT(id_user) as counter
FROM $table_jobs WHERE id_user = :id_user3
Will give something like
what count
Questions 7
Marketplace 9
Jobs 3
And you can retrieve them as
$array = $stmt->fetch_all();
You will get an array like
Array
(
[Questions] => 7
[Marketplace] => 9
[Jobs] => 3
)

SQL Use Subquery results with NOT IN

I can imagine that question exists in some way, but I haven't found what I was looking for.
I need to remove the found values from the result I'm getting in the main query.
Consider the following:
The mainquery:
SELECT idTable
FROM tblTables
WHERE NOT IN idTables = ( **SUBQUERY HERE** )
AND dtSeats >= 4
LIMIT 1;
The subquery:
SELECT idTable
FROM tblTables,tblReservation
WHERE tblTables.idTable = tblReservation.fiTable
AND fiTime = 1
AND dtResDate = "2020-06-16"
In the tblTables there are idTable and dtSeats.
In the tblReservation are fiTime and dtResDate.
The subquery can get up to three rows.
I need to get the first free table with the lowest number of seats possible.
Thanks for helping me out!
Having the DDL and some sample data would be helpful, but I think what you are looking for is a NOT EXISTS clause. It returns everything in the outer query that doesn't match with a record in the inner query.
SELECT idTable
FROM tblTables tt
WHERE NOT EXISTS (
SELECT NULL FROM tblReservation tr WHERE tt.idTable = tr.idTable AND
tr.dtResDate = '2020-06-16'
)
AND dtSeats >= 4
ORDER BY tt.dtSeats
LIMIT 1

How do I send a query to get the sum of the two tables?

I want to get the sum of the two tables.
1-1.hospital_payment_data table
1-2.hospital_payment_data table data
2-1.advenced_payment table
2-2 advenced_payment table data
I want result
However, sending the query as follows results.
SELECT COUNT(IF(treatment_fees_check_division = '선수금',
treatment_fees_check_division, NULL)) AS COUNT,
SUM(CASE WHEN treatment_fees_check_division = '선수금'
THEN treatment_fees_difference END) + SUM(advenced_amount
) AS if_treatment_fees_check_division,
SUM(advenced_amount) AS sum_init_amount
FROM
(
SELECT treatment_fees_check_division, treatment_fees_difference,
init_amount, advenced_amount
FROM hospital_payment_data , advenced_payment
)AS a
bad result
How do I fix the query? I'd like your posture, please.
Is this what you are looking for?
SELECT ( SELECT SUM(...) FROM t1 ... ) +
( SELECT SUM(...) FROM t2 ... ) AS sum_of_tables

MYSQL SELECT including COUNT within the same table with reference to specific column

So, I'm getting data from one table with a simple SELECT statement with SELECT COUNT included.
SELECT *,
(SELECT COUNT(`message_id`)
FROM `user_message`
WHERE `status_to` = 0
) AS `unread`
FROM `user_message`
Here, unread counts for unread messages coming from other users. But that's not quite enough. What I want is to reference SELECT COUNT to a specific column, user_id, within the same table:
SELECT *,
(SELECT COUNT(`message_id`)
FROM `user_message`
WHERE `status_to` = 0 AND `user_message`.`user_id` = `user_message`.`user_id`
) AS `unread`
FROM `user_message`
.. if that makes sense. My second statement disregards this part: AND user_message.user_id = user_message.user_id, and gives me the same result for each user_id.
What am I missing??
You need to give different aliases to your table to get the related count
SELECT *, (
SELECT COUNT(`message_id`)
FROM `user_message` b
WHERE `status_to` = 0
AND `a`.`user_id` = `b`.`user_id`
) AS `unread`
FROM `user_message` a

How to make a where clause where the value is an array from a previous sql query

I have a small list of data which is from an SQL database and uses mysql_fetch_array($query_run) to get it. This all works fine and I can echo out that data to double check it.
But where I want to use it is another SQL query, but where it doesn't equal it. My code at the moment only doesn't include one of the data items. So, I'm guessing you have to do something to let it know it's an array not just one piece of data?
Here's my code:
$query = "SELECT * FROM myFriends WHERE idPerson = '$loggedInUserId'";
$query_run = mysql_query($query);
while($row = mysql_fetch_array($query_run)) {
$idfriend = $row['idFriend'];
$queryFrirend = "SELECT * FROM perosn WHERE idPerson != '$idfriend'
Any help would be great!
Personally, I wouldn't bother with turning an array into a WHERE clause, if the set is returned from a MySQL query. Relational databases are built for this kind of thing.
A query with the familiar anti-join pattern will return the specified result:
SELECT p.*
FROM person p
LEFT
JOIN myFriends f
ON f.idFriend = p.idPerson
AND f.idPerson = '$loggedInUserId'
WHERE f.idFriend IS NULL
This says get all rows from the person table, and match to rows from the myFriends table. The WHERE clause says to exclude rows where a matching row was found, leaving only rows from person that didn't have a matching row returned from myFriends. With appropriate indexes, MySQL can blaze through that, without the overhead of sending a list of id values in a WHERE clause.
But, that doesn't really answer the question you asked.
The SQL you specified, including a list of idPerson values to be excluded, can be of several forms:
SELECT p.*
FROM person p
WHERE p.idPerson NOT IN (2,3,5,7,11,13,15,17,19)
or
SELECT p.*
FROM person p
WHERE p.idPerson <> 2
AND p.idPerson <> 3
AND p.idPerson <> 5
AND p.idPerson <> 7
AND p.idPerson <> 11
AND p.idPerson <> 13
AND p.idPerson <> 15
AND p.idPerson <> 17
or
SELECT p.*
FROM person p
WHERE NOT EXISTS
( SELECT 1
FROM ( SELECT 2 AS idPerson
UNION ALL SELECT 3
UNION ALL SELECT 5
UNION ALL SELECT 7
UNION ALL SELECT 9
UNION ALL SELECT 11
UNION ALL SELECT 13
UNION ALL SELECT 15
UNION ALL SELECT 17
UNION ALL SELECT 19
) f
WHERE f.idPerson = p.idPerson
)
or
SELECT p.*
FROM person p
LEFT
JOIN ( SELECT 2 AS idPerson
UNION ALL SELECT 3
UNION ALL SELECT 5
UNION ALL SELECT 7
UNION ALL SELECT 9
UNION ALL SELECT 11
UNION ALL SELECT 13
UNION ALL SELECT 15
UNION ALL SELECT 17
UNION ALL SELECT 19
) f
ON f.idPerson = p.idPerson
WHERE f.idPerson IS NULL
It's just a matter of looping through the rows in the result set, and using that value to format an appropriate SQL statement. The easiest approach (apart from aforementioned avoidance of having to run two separate queries to get the resultset you want), would be to build an array of the friendId column values. And then turn that array into a string of comma separated literals 2,3,5,7,9,11,13,17,19. Of course, you'd need to handle the edge case of no rows returned, because foo NOT IN () isn't valid SQL syntax.
If you want to build the statement on the fly, as you loop through the rows, you could do something like this:
$queryFrirend = "SELECT * FROM person WHERE 1=1";
while($row = mysql_fetch_array($query_run)) {
$queryFrirend .= " AND idPerson <> " . (int) $row['idFriend'];
}
$queryFrirend .= " ORDER BY idPerson";
echo "SQL=", $queryFrirend;
Though that's going to some ugly SQL. (I don't want to be around when the DBA comes hunting for you.)
You can't use arrays in SQL queries. You need to turn the array into a String of values separated by commas, and use IN().
SELECT * FROM perosn WHERE idPerson Not IN ('person1', 'person2')

Categories