No order in MySQL query - mysql

I have this query
Select nametwo
from cities
inner join usuarios
where cities.nametwo=usuarios.jug1
or cities.nametwo=usuarios.jug2
or cities.nametwo=usuarios.jug3
and the data is
jug1 = 2 jug2 = 1 jug3 = 4
then, the query order the data by ASC, and I want that order it by the order of the select.
is there a way for do this? thanks

Seems that you are wanting to order by the usuarios table unless I am misunderstanding.
Select nametwo
from cities
inner join usuarios
where cities.nametwo=usuarios.jug1
or cities.nametwo=usuarios.jug2
or cities.nametwo=usuarios.jug3
order by usuarios

First, if you use inner join, use an on clause. This is required in every database except MySQL and it just looks really awkward. Here is an equivalent query:
Select c.nametwo
from cities c inner join
usuarios u
on c.nametwo in (u.jug1, u.jug2, u.jug3);
This formulation actually directly suggests the answer. Use the field() function:
order by field(c.nametwo, u.jug1, u.jug2, u.jug3)

Related

MySQL INNER JOIN, get the last entries, not the first

I am having an issue with my multi join SQL statement, where I need to get the last entries of the table and not the first. I have 3 tables that I try to query based on this statement:
SELECT DISTINCT i.id,i.hz,i.v,i.t,i.u,i.temp, i.c1, s.server, s.hostname, h.codes,s.cpus FROM `dc_servers` AS s INNER JOIN `dc_hardware` AS h ON s.server = h.server INNER JOIN `dc_systemusage` AS i ON s.server = i.server GROUP BY i.server
The tables dc_servers & dc_hardware only has 1 row per server, however the table dc_systemusage has many rows with the same server, as new info is being added.
When I run the query, I get the first entries from the dc_systemusage, but I need to get the latest entries from that table, for me it sounds like I need an ORDER BY, however if I add that to the end of the query like this:
SELECT DISTINCT i.id,i.hz,i.v,i.t,i.u,i.temp, i.c1, s.server, s.hostname, h.codes,s.cpus FROM `dc_servers` AS s INNER JOIN `dc_hardware` AS h ON s.server = h.server INNER JOIN `dc_systemusage` AS i ON s.server = i.server GROUP BY i.server ORDER BY i.id DESC
then I am just ordering the result, which is not what I am looking for.
I hope someone can guide me in the right direction as for how I can get the latest rows and not the first from the table dc_systemusage
I hope I have provided the needed information to guide me, else please do let me know and I will add whatever is neeeded.
Thank you all.
You can find dc_systemusage lastest ids in subquery and use with WHERE ... IN
SELECT i.id,i.hz,i.v,i.t,i.u,i.temp, i.c1, s.server, s.hostname, h.codes,s.cpus
FROM `dc_servers` AS s
INNER JOIN `dc_hardware` AS h ON s.server = h.server
INNER JOIN `dc_systemusage` AS i ON s.server = i.server
WHERE i.id IN (SELECT max(dc_systemusage.id) FROM dc_systemusage GROUP BY dc_systemusage.server)
and check a great answer at https://stackoverflow.com/a/3800572/7174186

Order using count from another table

Hi I need to Order using count from another table. i found this great example, im using it as model for a query i need. SQL - How To Order Using Count From Another Table
The model im using for query is:
SELECT bloggers.*, COUNT(post_id) AS post_count
FROM bloggers LEFT JOIN blogger_posts
ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
But i have a syntax problem in mine, i guess, im trying to replace the next query, with the one that counts another table... but i cant manage to do it. Original query:
$res3=$db->execute_query("select id,scode,sname from ".TABLE_PREFIX."states where ccode=? order by sname asc",array($country));
Trying to replace with this query..
$res3=$db->execute_query("select ".TABLE_PREFIX."states.* , COUNT(".TABLE_PREFIX."items.state) AS state_count FROM ".TABLE_PREFIX."states LEFT JOIN ".TABLE_PREFIX."items ON ".TABLE_PREFIX."states.id = ".TABLE_PREFIX."items.state GROUP BY ".TABLE_PREFIX."states.id ORDER BY state_count DESC",array($country));
Try this:
$res3=$db->execute_query("select a.* , COUNT(b.state) AS state_count FROM states a
LEFT JOIN items b ON a.id = b.state
GROUP BY a.id
ORDER BY state_count DESC",array($country));

Creating a subquery in Access

I am attempting to create a subquery in Access but I am receiving an error stating that one record can be returned by this subquery. I am wanting to find the top 10 companies that have the most pets then I want to know the name of those pets. I have never created a subquery before so I am not sure where I am going wrong. Here is what I have:
SELECT TOP 10 dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgency
(SELECT dbo_tPet.Pet
FROM dbo_tPet)
FROM dbo_tPet INNER JOIN dbo_tGovenrnmentRegulatoryAgency ON
dbo_tPet.GovernmentRegulatoryAgencyID =
dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgencyID
GROUP BY dbo_tGovenrnmentRegulatoryAgency.GovernmentRegulatoryAgency
ORDER BY Count(dbo_tPet.PetID) DESC;
Consider this solution, requiring a subquery in the WHERE IN () clause:
SELECT t1.GovernmentRegulatoryAgency, dbo_tPet.Pet,
FROM dbo_tPet
INNER JOIN dbo_tGovenrnmentRegulatoryAgency t1 ON
dbo_tPet.GovernmentRegulatoryAgencyID = t1.GovernmentRegulatoryAgencyID
WHERE t1.GovernmentRegulatoryAgency IN
(SELECT TOP 10 t2.GovernmentRegulatoryAgency
FROM dbo_tPet
INNER JOIN dbo_tGovenrnmentRegulatoryAgency t2 ON
dbo_tPet.GovernmentRegulatoryAgencyID = t2.GovernmentRegulatoryAgencyID
GROUP BY t2.GovernmentRegulatoryAgency
ORDER BY Count(dbo_tPet.Pet) DESC);
Table aliases are not needed but I include them for demonstration.
This should hopefully do it:
SELECT a.GovernmentRegulatoryAgency, t.NumOfPets
FROM dbo_tGovenrnmentRegulatoryAgency a
INNER JOIN (
SELECT TOP 10 p.GovernmentRegulatoryAgencyID, COUNT(p.PetID) AS NumOfPets
FROM dbo_tPet p
GROUP BY p.GovernmentRegulatoryAgencyID
ORDER BY COUNT(p.PetID) DESC
) t
ON a.GovernmentRegulatoryAgencyID = t.GovernmentRegulatoryAgencyID
In a nutshell, first get the nested query sorted, identifying what the relevant agencies are, then inner join back to the agency table to get the detail of the agencies so picked.

MySQL - LIMIT selects 1 less then supposed

I'm trying to LIMIT the database output with 5, but it's only selecting 4. And yes, I'm sure there's more then 4.
$sql = "SELECT * FROM lookup
INNER JOIN lookupCategories
ON lookup.FK_lookupCategory=lookupCategories.lookupCategoriesId
INNER JOIN lookupType
ON lookup.FK_lookupType=lookupType.lookupTypeId
INNER JOIN authentication
ON lookup.FK_lookupUserId=authentication.userId
WHERE FK_lookupUserId='$_GET[id]'
ORDER BY lookupId DESC
LIMIT 5";
My code looks like this. What could be wrong? :)
Thanks in advance.
I would suggest that there are only 4 entries that match - to prove or disprove this, try your query without the LIMIT and see how many results are returned:
"SELECT COUNT(*) FROM lookup
INNER JOIN lookupCategories
ON lookup.FK_lookupCategory=lookupCategories.lookupCategoriesId
INNER JOIN lookupType
ON lookup.FK_lookupType=lookupType.lookupTypeId
INNER JOIN authentication
ON lookup.FK_lookupUserId=authentication.userId
WHERE FK_lookupUserId='$_GET[id]';

Multiple Joins Mysql Doubles SUM values

Im trying to make a a query, but its doubling the Sum values
SELECT
cidades.id AS id,
cidades.name AS municipio,
Sum(conjuntos.n_uhs) AS uh,
programas.id AS programa,
conjuntos.name
FROM
conjuntos
Inner Join conjuntos_programas ON conjuntos_programas.conjunto_id = conjuntos.id
Inner Join programas ON programas.id = conjuntos_programas.programa_id
Inner Join cidades ON conjuntos.cidade_id = cidades.id
WHERE
conjuntos.situation_id = 2
GROUP BY
conjuntos.cidade_id
ORDER BY
municipio ASC
You've got duplicate rows, you can check this by removing the group by and the SUM(... from your query.
Change the query as follows and tell me if that fixes to problem.
SELECT DISTINCT
cidades.id AS id,
cidades.name AS municipio,
SUM(conjuntos.n_uhs) AS uh,
programas.id AS programa,
conjuntos.name
FROM conjuntos
INNER JOIN conjuntos_programas ON conjuntos_programas.conjunto_id = conjuntos.id
INNER JOIN programas ON programas.id = conjuntos_programas.programa_id
INNER JOIN cidades ON conjuntos.cidade_id = cidades.id
WHERE conjuntos.situation_id = 2
GROUP BY conjuntos.cidade_id
ORDER BY municipio ASC
It sounds like you have a one to many relationship between two or more of your tables to be doing this. Try doing a SELECT * and start debugging your query to see where it is duplicating the rows.