Compare string to same column in multiple tables mysql - mysql

i have a string referring to a jpg file, let's say '34563.jpg'.
Now i want to know if this file is assigned to any record in this 3 tables.
All 3 tables has the same structure
id,name,img
My query just returns true to the first table:
SELECT clients_tbl.img, pets_tbl.img, places_tbl.img
FROM clients_tbl, pets_tbl, places_tbl
WHERE (clients_tbl.img = '34563.jpg')
OR (pets_tbl.img = '34563.jpg')
OR (places_tbl.img = '34563.jpg');
I need a boolean response from this query, it has been found or not.
Thanks

You need UNION:
SELECT COUNT(t.*) when_not_found_0
FROM (
SELECT img
FROM clients_tbl
WHERE clients_tbl.img = '34563.jpg'
UNION
SELECT img
FROM pets_tbl
WHERE pets_tbl.img = '34563.jpg'
UNION
SELECT img
FROM places_tbl
WHERE places_tbl.img = '34563.jpg'
) t

You could set aliases:
SELECT clients_tbl.img as img_clients, pets_tbl.img as img_pets, places_tbl.img as img_places
And later turn the results to booleans.

Related

How to access columns of subqueries with jooq?

i am having troubles understanding how to access columns from a subquery (MySQL). Here is my code:
Personne personne = Personne.PERSONNE.as("personne");
Evenement evenement = Evenement.EVENEMENT.as("evenement");
Genealogie genealogie = Genealogie.GENEALOGIE.as("genealogie");
Lieu lieu = Lieu.LIEU.as("lieu");
SelectField<?>[] select = { DSL.countDistinct(personne.ID).as("countRs"), lieu.LIBELLE.as("libelleRs"),
lieu.ID.as("idVille") };
Table<?> fromPersonne = evenement.innerJoin(personne).on(personne.ID.eq(evenement.IDPERS))
.innerJoin(genealogie).on(genealogie.ID.eq(personne.IDGEN)).innerJoin(lieu)
.on(lieu.ID.eq(evenement.IDLIEU));
Table<?> fromFamille = evenement.innerJoin(personne).on(personne.IDFAM.eq(evenement.IDFAM))
.innerJoin(genealogie).on(genealogie.ID.eq(personne.IDGEN)).innerJoin(lieu)
.on(lieu.ID.eq(evenement.IDLIEU));
GroupField[] groupBy = { lieu.ID };
Condition condition = //conditionally build, not relevant i think
result = create.select(DSL.asterisk())
.from(create.select(select).from(fromPersonne).where(condition).groupBy(groupBy)
.union(create.select(select).from(fromFamille).where(condition).groupBy(groupBy)))
// i would like something like this but i don't know how: .groupBy(groupBy).fetch();
Basicly what i have is:
SELECT
*
FROM(
(SELECT
countRs, libelleRs, idVille
FROM
fromPersonne
WHERE
-- conditions
GROUP BY lieu.ID)
UNION
(SELECT
countRs, libelleRs, idVille
FROM
fromFamille
WHERE
-- conditions
GROUP BY lieu.ID)
)GROUP BY lieu.ID -- this is where i need help
In a plain MySQL query i would just give an alias to the union and then make a reference to the column i want to group by using the alias but it seems like it does not work like this with JOOQ.
I just need to group the results of the subqueries together but i don't know how to make a reference to the subqueries columns... I am sure i would have to reference my subqueries in objects outside of that "main select" to be able to access the columns or something along those lines but i am lost in all the object types.
You have to assign your derived table to a local variable and dereference columns from it, e.g.
Table<?> t = table(
select(...).from(...).groupBy(...).unionAll(select(...).from(...).groupBy(...))
).as("t");
Field<Integer> tId = t.field(lieu.ID);

Query table based on input parameter

I have an input parameter to a query I'm trying to write. Basically, if mostRecentSnapshot == true then I want to select only the most recent records from the process run (basically where max(creationDate)) and if mostRecentSnapshot == false then select creationDate and other columns normally.
To me, it makes sense to do this if statement in the from clause, but I don't think that's possible. Normally I would use a CTE, but I those don't exist in MySQL.
What is the best way to achieve this?
It would be something along the lines of this:
SELECT
CASE mostRecentSnapshot WHEN FALSE THEN
(
processauditheader.creationDate as processCreationDate,
processauditheader.processName,
processauditheader.processType,
processauditheader.processHost,
processauditheader.processDatabase,
processauditheader.tableAudited,
processauditheader.processInvokedByName,
processauditheader.processInvokedByType,
processauditheader.processInvokedByDatabase,
processauditheader.processIntervalValue,
processauditheader.processIntervalField,
processauditheader.auditScenarios,
processaudititerationdetail.creationDate as iterationDate,
processaudititerationdetail.connectionId,
processaudititerationdetail.processDate,
processaudititerationdetail.tableRowCount,
processaudititerationdetail.tableRowCountLastDay,
processaudititerationdetail.previousProcessAuditIterationDetailID,
processauditmetricdetail.creationDate,
processauditmetricdetail.processAuditIterationDetailID,
processauditmetricdetail.auditMetric,
processauditmetricdetail.auditTotal,
processauditmetricdetail.auditExample
)
WHEN TRUE THEN
(
((SELECT MAX(processaudititerationdetail.creationDate) as maxSnapshot,
processaudititerationdetail.id
from reporting_audit.processaudititerationdetail
group by processaudititerationdetail.creationDate) mostRecent
JOIN reporting_audit.processaudititerationdetail ON mostRecent.id = processaudititerationdetail.id)
)
END
FROM reporting_audit.processauditheader
JOIN processaudititerationdetail ON processaudititerationdetail.processAuditHeaderID = processauditheader.id
LEFT JOIN processauditmetricdetail ON processauditmetricdetail.processAuditIterationDetailID = processaudititerationdetail.id
A query can only return a fixed set of columns. Perhaps the following does what you want:
select paid.*
from reporting_audit.processaudititerationdetail paid
where (not v_mostRecentSnapshot) or
paid.creation_date = (select max(paid2.creationDate from reporting_audit.processaudititerationdetail paid2);
It will either select all records from the table or only the record(s) that have the most recent creationDate.

JOIN on keys that don't have the same value

I am trying to do an INNER JOIN on two tables that have similar values, but not quite the same. One table has a fully qualified host name for its primary key, and the other the hosts short name, as well as the subdomain. It it safe to assume that the short name and the subdomain together are unique.
So I've tried:
SELECT table1.nisinfo.* FROM table1.nisinfo INNER JOIN table2.hosts ON (table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com') = table2.hosts.fqhn WHERE table2.hosts.package = 'somepkg';
This doesn't return the results I expect, it returns the first result hundreds of times. I'd like to return distinct rows. It takes a long time to run as well.
What am I doing wrong? I was thinking of running a subquery to get the hostnames, but I don't know what the right path from here is.
Thank you!
You can use group by in your query so you can achieve the desired results you want
please see this two links
Group by with 2 distinct columns in SQL Server
http://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tables
Try putting your results into a temp table and then view the table to make sure that the columns are as expected.
SELECT table1.nisinfo.*, table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com' AS ColID
INTO #temp
FROM table1.nisinfo;
Select *
from #temp INNER JOIN table2.hosts ON ##temp.ColID = table2.hosts.fqhn
WHERE table2.hosts.package = 'somepkg'
;
Put a Group By clause at the end of the second statement
So in this case, I used a subquery to get the initial results, and then used a join.
SELECT table1.nisinfo.* FROM table1.nisinfo JOIN (SELECT distinct(fqhn) FROM table2.hosts WHERE package = 'bash') AS FQ ON ((SUBSTRING_INDEX(FQ.fqhn, '.', 1)) = table1.nisinfo.shortname);

MySQL Join of two SELECT result

I have two select:
SELECT ID, ID_cat, modello
FROM tbArticoli
WHERE ID_cat=5
Example result in Json:
{"ID":"5","ID_cat":"5","modello":"Hawaii"},
{"ID":"6","ID_cat":"5","modello":"T-Shirt Righe"},
{"ID":"7","ID_cat":"5","modello":"Polo"},
{"ID":"8","ID_cat":"5","modello":"Fantasia"},
{"ID":"9","ID_cat":"5","modello":"Fiori"},
{"ID":"10","ID_cat":"5","modello":"Arcobaleno"},
{"ID":"11","ID_cat":"5","modello":"Oro"},
{"ID":"12","ID_cat":"5","modello":"Argento"},
{"ID":"13","ID_cat":"5","modello":"StelleStrisce"}
And another select:
SELECT IDModello,
FLOOR(AVG(voto)) AS votomedio
FROM tbCommenti
GROUP BY IDModello
with result:
{"IDModello":"5","votomedio":"7"},
{"IDModello":"6","votomedio":"7"},
{"IDModello":"7","votomedio":"8"},
{"IDModello":"8","votomedio":"6"}
I need a final result like this:
{"ID":"5","ID_cat":"5","modello":"Hawaii","votomedio":"7"},
{"ID":"6","ID_cat":"5","modello":"T-Shirt Righe","votomedio":"7"},
{"ID":"7","ID_cat":"5","modello":"Polo","votomedio":"8"},
{"ID":"8","ID_cat":"5","modello":"Fantasia","votomedio":"6"},
{"ID":"9","ID_cat":"5","modello":"Fiori","votomedio":"null"},
{"ID":"10","ID_cat":"5","modello":"Arcobaleno","votomedio":"null"},
{"ID":"11","ID_cat":"5","modello":"Oro","votomedio":"null"},
{"ID":"12","ID_cat":"5","modello":"Argento","votomedio":"null"},
{"ID":"13","ID_cat":"5","modello":"StelleStrisce","votomedio":"null"}
on tbArticoli.ID = tbCommenti.IDModello
Which is the best query?
Thank you.
Assuming you want to join on id = idmodello, you can do something like
SELECT *
FROM (SELECT ID, ID_cat, modello
FROM tbArticoli
WHERE ID_cat=5) AS tbA
LEFT JOIN (SELECT IDModello,
FLOOR(AVG(voto)) AS votomedio
FROM tbCommenti
GROUP BY IDModello) as tbC
ON tbA.ID = tbC.IDModello
You can specify subqueries as what you are selecting from, because MySQL selects from a set of tuples. The table name just specifies that you want all tuples from that table, whereas in the query above you are specifying the specific tuples that you want. The main thing to note in this query is that you must use the 'AS' keyword to specify a temp name for each set of tuples.

Nested MySQL query?

I have this MySQL statement which works fine:
SELECT claim_items.item_id, claim_items.quantity*items_rate.rate as per_item
FROM claim_items, items_rate
WHERE claim_items.claim_id = 1 AND claim_items.item_id = items_rate.items_id
However what I want to do is to get the sum of the per_item field generated in the MySQL statement. Is it possible to do a nested statement to do that? I know I could create a view and then do it, but would prefer to do it in one statement.
Thanks for your help, much appreciated!
select t.id, SUM(t.per_item)
from
(
SELECT claim_items.item_id as id, claim_items.quantity*items_rate.rate as per_item
FROM claim_items, items_rate
WHERE claim_items.claim_id = 1 AND claim_items.item_id = items_rate.items_id
) t
group by t.id
Hope this should help.
If you just want the sum over all rows you can do it like that (using explicit joins for better readability):
SELECT SUM( claim_items.quantity * items_rate.rate )
FROM claim_items
JOIN items_rate ON ( items_rate.items_id = claim_items.item_id )
WHERE claim_items.claim_id = 1