How to use a result from a query with ORDER BY clause? - php

I want to order the result based on another query. Here's my query:
"SELECT * FROM red_table INNER JOIN blue_table ON red_table.ID = blue_table.ID";
I'd like to add ORDER BY using the result from another query:
"SELECT date FROM blue_table WHERE status = 'ready'";
So the final will be something like:
"SELECT * FROM red_table INNER JOIN blue_table ON red_table.ID = blue_table.ID ORDERY BY ( SELECT date FROM blue_table WHERE status = 'ready' )";
How do I do that? Or is it possible?
UPDATE:
I know I could just use ORDER BY blue_table.date but the date column contains values that are not Date. blue_table is kind of a metadata table. So I need to match the values from the date column with the status column so I only get the date values and use that for ordering. Maybe I shouldn't have called it column date but I hope you get my point.

Maybe you mean something like this? You would have to add additional column names in select
SELECT status, date
FROM red_table INNER JOIN blue_table ON red_table.ID = blue_table.ID
GROUP BY 1, 2

SELECT *
FROM red_table
INNER JOIN blue_table ON red_table.ID = blue_table.ID
WHERE blue_table.status = 'ready'
ORDER BY blue_table.date
Note that if blue_table does not contain a match for the join condition, nothing from red_table will be shown.

Related

While using a SELECT SUM() GROUP BY, how can I still get the individual values?

values = 2,3,4
When doing a JOIN (SELECT *, SUM(values) AS MaxValues FROM table GROUP BY id), $a = $data['MaxValues'] will equal 9 as it should. However, how can I still pull the individual values(2,3,4)? trying a foreach on $b = $data['values'] only gives me one of the values. I'm assuming because of the required GROUP BY. I'm still new to all of this. Thank you
You are looking for group_concat(), I think:
JOIN (SELECT id, SUM(values) AS MaxValues, group_concat(values) as values
FROM table
GROUP BY id)
Note: You should not be using SELECT * with GROUP BY. Only include the columns in the GROUP BY clause.
You can select both values and SUM with JOIN. Also, you don't need GROUP BY if you want to get all the values, e.g.:
SELECT value, a.sum
FROM table, (SELECT SUM(value) AS `sum` FROM table ) a;

How to remove duplicate values from an sql query

I want to know how to remove duplicate values from the output of an sql query.
This is the sql query:
$query = "SELECT useraccount.Username, tariff.Name as tariffs,
energyconsumption.ElecEnergy, useraccount.Username as User
FROM useraccount
INNER JOIN tariff
ON useraccount.tariffs = tariff.id
INNER JOIN energyconsumption
ON energyconsumption.User = useraccount.id
WHERE Date = CURRENT_DATE";
This is the output of that query:
{"results":[{"Username":"absc868","TariffName":"s1","ElecConsump":"2000"},
{"Username":"absc868","TariffName":"s1","ElecConsump":"1900"}]}
As you can see, the query filters out data where the data matches todays date. We have 2 outputs for the same user. The value of the tariff name and username are the same,but the energy consumption value is different which is fine.
I want to achieve the following output:
= {"results":[{"Username":"absc868","TariffName":"s1","ElecConsump":"2000 +1900"}
= {"results":[{"Username":"absc868","TariffName":"s1","ElecConsump":"3900"}
Could someone point me to the direction in how I can achieve this?
Thank you in advance to those who read the post and contributed!
You can use the group_concat function:
$query = "SELECT useraccount.Username, tariff.Name as tariffs,
GROUP_CONCAT(energyconsumption.ElecEnergy SEPARATOR ' +')
FROM useraccount
INNER JOIN tariff
ON useraccount.tariffs = tariff.id
INNER JOIN energyconsumption
ON energyconsumption.User = useraccount.id
WHERE Date = CURRENT_DATE
GROUP BY useraccount.Username, tariff.Name";
You should use a sum and a group by
$query = "SELECT useraccount.Username as Username, tariff.Name as TariffName,
sum(energyconsumption.ElecEnergy) as ElecConsump
FROM useraccount
INNER JOIN tariff
ON useraccount.tariffs = tariff.id
INNER JOIN energyconsumption
ON energyconsumption.User = useraccount.id
WHERE Date = CURRENT_DATE
GROUP BY useraccount.Username, tariff.Name as tariffs";
(you have some difference between table column name alias and object attribute name )

SQL Query Syntax error?

I am trying to modify a query which results in 2 records before the modification for some reason my modification makes it not work as it return nothing.
This Query works and returns 2 record:
$query = mysql_query("SELECT * FROM `table1`
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
...the I added this: JOIN table2 USING(id)
...so this final code is this:
$query = mysql_query("SELECT * FROM `table1` JOIN `table2` USING(id)
WHERE `date` = '{$eventdate->format('Y-m-d')}'
OR `date` >= CURDATE() ORDER BY id DESC");
Problem is the second one returns nothing.
Is this a syntax error? How can I get this to work? Both tables have id fields.
Make sure that table2 contains matched data, where the id is equal to the id in table1.
You can use a LEFT JOIN if this match is not required.
id in your ORDER BY is now ambiguous. There might be more errors though. Check with mysql_error()
Try This
$query = mysql_query("SELECT * FROM `table1` a,`table2` b WHERE a.id=b.id
and (`a.date` = '{$eventdate->format('Y-m-d')}' OR `a.date` >= CURDATE())
ORDER BY id DESC")
When joining two tables which have no prefixes on the column names like - table1_id, table2_id, you should use aliases like -
SELECT * FROM table1 as t1 JOIN table2 as t2 on ...
and then you can refer to the fields in the table like this - t1.id, t2.id (you can do this also without aliases( as t1) and then you should refer to the fields like - table1.id).
The problem with your script is that the 2 tables have column id and in :
ORDER BY id DESC
the engine doesn`t know from which table do you refer this id
Other suggestion of mine is when possible not to use aggregation functions in the queries(in your query the CURDATE is that type of function). Aggregation functions in SQL prevent query caching. In our case you can pass the currdate from php to the query and the query can be cached.
Hope i`ve helped.

sorting mysql table by data within a different table

I have to mysql tables and trying to display results of table1 but sorting by table2. For table2 I'm counting all the occurrences of a duplicate id and then display that result descending. Below is as far as I could get and wondering if this can even be done is a single query.
$query = "
SELECT DISTINCT registration.*
FROM registration
INNER JOIN downloads
ON registration.id = downloads.id
GROUP BY downloads.COUNT(id)
ORDER BY downloads.COUNT(id) DESC,
downloads.COUNT(id) DESC
";
I think you want something along these lines:
SELECT Registration.id, Registration.name, Registration.email,
Downloads.document
FROM Registration
JOIN Downloads
ON Downloads.id = Registration.id
JOIN (SELECT id, COUNT(*) as count
FROM Downloads
GROUP BY id) Download_Count
ON Download_Count.id = Registration.id
ORDER BY Download_Count.count DESC
(untested, as it would be nice for the OP to supply sample data and table layouts in the question)

Combine to two tables within a single query to order data

I have two tables word_term_relationships and word_posts
What I'm doing is using a while loop in order to fetch a certain record from the word_term_relationships table where a certain value is true.
$query = "SELECT object_id
FROM `word_term_relationships`
WHERE `term_taxonomy_id` = '54'";
I then use another query within the loop to use the data that was retrieved from the previous query in order to fetch data from the other table word_posts
$query2 = "SELECT post_title, post_date, post_date_gmt, guid
FROM `word_posts`
WHERE `ID` = '$post_id'";
This I can do and works fine.
The only issue is that I then need to order the results by date and time, I can do this without the while loop and using the ORDER BY function and the word_posts table.
However, I've tried to link the tables within the query like this (below) in order to order the data. But obviously it isn't correct - I just can't pinpoint within the query what is wrong.
$query = "SELECT word_term_relationships.object_id
FROM word_term_relationships
WHERE word_term_relationships.term_taxonomy_id = '54'
ORDER BY word_posts.post_date ASC";
I know the above query is missing something, I was thinking a second where after the ORDER BY word_posts.post_date ASC.
A simple INNER JOIN will solve your problem. Try this,
SELECT a.post_title,
a.post_date,
a.post_date_gmt,
a.guid
FROM word_posts a
INNER JOIN word_term_relationships b
ON a.ID = b.object_id
WHERE b.term_taxonomy_id= '54'
ORDER BY a.post_date ASC
$query = "SELECT post_title
, post_date
, post_date_gmt
, guid
FROM word_posts a INNER JOIN word_term_relationships b on a.ID = b.object_id
WHERE term_taxonomy_id = '54'
ORDER BY a.post_date ASC";

Categories