check if exist record in the another table - mysql

task; id
task_assign; id, task_id
task_state; id, assign_id
states; id, state_id, define_id
I want containing at selected IDs in other table
SELECT DISTINCT t.id,t.* FROM tasks AS t
INNER JOIN task_assign AS ta1 ON ta1.task_id=t.id
INNER JOIN task_state AS ts1 ON ts1.assign_id=ta1.id
INNER JOIN states AS s1 ON s1.id=ts1.state_id AND s1.define_id=14
INNER JOIN task_assign AS ta2 ON ta2.task_id=t.id
INNER JOIN task_state AS ts2 ON ts2.assign_id=ta2.id
INNER JOIN states AS s2 ON s2.id=ts2.state_id AND s2.define_id=21
.
.
.
INNER JOIN task_assign AS ta5 ON ta5.task_id=t.id
INNER JOIN task_state AS ts5 ON ts5.assign_id=ta5.id
INNER JOIN states AS s5 ON s5.id=ts5.state_id AND s5.define_id=25
this works but when multiplied request it slowing down. Is there another method?

SELECT
t.id
FROM
tasks t
INNER JOIN
task_assign ta1
ON ta1.task_id = t.id
INNER JOIN
task_state ts1
ON ts1.assign_id = ta1.id
INNER JOIN
states s1
ON s1.id = ts1.state_id
AND s1.define_id IN (14,25)
GROUP BY
t.id
HAVING
COUNT(DISTINCT s1.define_id) = 2
EDIT - to explain to the OP what this does...
This will first retrieve all records where the define_id is either 14 OR 25, but the HAVING clause will only allow the query to return those who have both.

Related

How to join 4 tables with mysql

Sorry, now here is the code, basically, the first query returns me a tab which contains fk_id_produto, i wanted to join it with thee second one with the id_pedido
(SELECT fk_id_produto,fk_id_pedido, descricao_produto, valor_produto
FROM Pedido_Produto
INNER JOIN Produto ON pedido_produto.fk_id_produto = produto.id_produto);
INNER JOIN ON
(SELECT id_cliente,nome_cliente,id_pedido,valor_pedido,data_do_pedido A
FROM Cliente
INNER JOIN Pedido ON cliente.id_cliente = pedido.fk_id_cliente);
You can just do a join with the two selects that you have
SELECT *
FROM
(SELECT 1) as s1 inner join
(SELECT 2) as s2 on s1.id_pedido = s1.fk_id_pedido
SELECT *
FROM
(SELECT
fk_id_produto,
fk_id_pedido,
descricao_produto,
valor_produto
FROM
Pedido_Produto
INNER JOIN Produto
ON pedido_produto.fk_id_produto = produto.id_produto
) as s1
INNER JOIN
(SELECT
id_cliente,
nome_cliente,
id_pedido,
valor_pedido,
data_do_pedido A
FROM
Cliente
INNER JOIN Pedido
ON cliente.id_cliente = pedido.fk_id_cliente
) as s2
ON s1.id_pedido = s1.fk_id_pedido
BR
So you have four tables:
Products (P)
Clients (C)
Orders (O)
OrderProducts (OP)
SELECT
*
FROM
OP
JOIN
P ON P.ID = OP.P_ID
JOIN
O ON O.ID = OP.O_ID
JOIN
C ON C.ID = O.C_ID
That will produce one row for each OP and give you the product, order and client details

Select the first record of another table inside a select - MYSQL

I´m trying to make a query listing all clients, and also get the last comment and
the date of that comment inside the table of history_client inside a single query for it to be listed.
select a.id_client,a.name,a.lastname,(select b.date_created,b.comentary
from history_of_client b where a.id_client = b.id_client_asociate) from clients_main_table
You could use an inner join on max(date_created) for id_client on history table and join
SELECT a.id_client,a.name,a.lastname, h.commentary
FROM clients_main_table a
INNER join (
select b.id_client_asociate, max(b.date_created) max_date
from history_of_client
group by b.id_client_asociate ) t on t.id_client_asociate = a.id_client
INNER JOIN history_of_client h on h.id_client_asociate = t.id_client_asociate
and h.date_created = t.max_date
Use the LEFT JOIN and INNER join to get your desired result set.
select a.id_client,
a.name,
a.lastname,
hc.date_created,
hc.comentary
from clients_main_table c
left join (select id_client_asociate,max(date_created) dt from history_of_client group by id_client_asociate) h
on (c.id_client = b.id_client_asociate)
inner join history_of_client hc
on (hc.id_client_asociate = b.id_client_asociate and hc.date_created = h.date_created)

Using SUM function in an update query with inner joins

Getting an error when running this
UPDATE FlightBooking
INNER JOIN Passenger ON Passenger.FlightBookingId=FlightBooking.FlightBookingId
INNER JOIN AirplaneSeat ON AirplaneSeat.AirplaneSeatId = Passenger.SeatId
INNER JOIN Section ON AirplaneSeat.SectionId = Section.SectionId
INNER JOIN ExtraCost ON ExtraCost.FlightBookingId=FlightBooking.FlightBookingId
INNER JOIN Luggage ON Luggage.LuggageId = ExtraCost.LuggageId
INNER JOIN SportsEquipment ON ExtraCost.SportsEquipmentId=SportsEquipment.SportsEquipmentId
INNER JOIN Insurance ON ExtraCost.InsuranceId = Insurance.InsuranceId
INNER JOIN CarHirePrice ON CarHirePrice.CarHirePriceId= ExtraCost.CarHirePriceId
INNER JOIN Route ON FlightBooking.RouteId = Route.RouteId
SET FlightBooking.TotalCost = (SUM(Section.PriceInflux+Route.RoutePrice+Luggage.Price+SportsEquipment.SportsEquipmentPrice+Insurance.Price+CarHirePrice.TotalPrice))
WHERE FlightBooking.FlightBookingId=1;
When I have it formed as a Select query it returns the correct value so all the tables are fine. I'm assuming my syntax is wrong.
Any help would be appreciated.
You should use the following syntax when using an aggregate in an update statement.
UPDATE t1
SET t1.field = t2.field2Sum
FROM table1 t1
INNER JOIN (select field3, sum(field2) as field2Sum
from table2
group by field3) as t2
on t2.field3 = t1.field3
See Below, I only scripted a few tables but you can see how to do the rest.
UPDATE FlightBooking set TotalCost = (ExtraCost.SumExtra + SumLuggage) From FlightBooking
INNER JOIN Passenger ON Passenger.FlightBookingId=FlightBooking.FlightBookingId
INNER JOIN AirplaneSeat ON AirplaneSeat.AirplaneSeatId = Passenger.SeatId
INNER JOIN Section ON AirplaneSeat.SectionId = Section.SectionId
INNER JOIN (Select FlightBookingId, sum(ExtraCost) as SumExtra from Extracost Group by FlightBookingId) as ExtraCost
ON ExtraCost.FlightBookingId=FlightBooking.FlightBookingId
INNER JOIN (Select FlightBookingId, sum(Price) as SumLuggage from Luggage Group by FlightBookingId) as Luggage
ON Luggage.FlightBookingId=FlightBooking.FlightBookingId
Are you sure that you have multiple records that match a single booking id?
If not, you can dispense with the sum():
SET FlightBooking.TotalCost = (Section.PriceInflux+Route.RoutePrice+Luggage.Price+SportsEquipment.SportsEquipmentPrice+Insurance.Price+CarHirePrice.TotalPrice)
If not, you'll need to pre-aggregate the tables that could generate multiple rows. In fact, you need to do this anyway to get a valid result (Cartesian products generated by joins will throw off the over sum).
many different possibilities for using aggregate funtion with update and inner join
UPDATE flight
SET flight.TotalCost = t.sumPrice
FROM FlightBooking AS flight
INNER JOIN
(
SELECT SUM(Section.PriceInflux+Route.RoutePrice+Luggage.Price+SportsEquipment.SportsEquipmentPrice+Insurance.Price+CarHirePrice.TotalPrice)) as sumPrice
FROM Passenger ON Passenger.FlightBookingId=flight.FlightBookingId
INNER JOIN AirplaneSeat ON AirplaneSeat.AirplaneSeatId = Passenger.SeatId
INNER JOIN Section ON AirplaneSeat.SectionId = Section.SectionId
INNER JOIN ExtraCost ON ExtraCost.FlightBookingId=flight.FlightBookingId
INNER JOIN Luggage ON Luggage.LuggageId = ExtraCost.LuggageId
INNER JOIN SportsEquipment ON ExtraCost.SportsEquipmentId=SportsEquipment.SportsEquipmentId
INNER JOIN Insurance ON ExtraCost.InsuranceId = Insurance.InsuranceId
INNER JOIN CarHirePrice ON CarHirePrice.CarHirePriceId= ExtraCost.CarHirePriceId
INNER JOIN Route ON flight.RouteId = Route.RouteId
) t
WHERE flight.bookingID = 1
also have a look to this examples
PC #PauloSantos and #OMGPonieshttps://stackoverflow.com/a/2009981/4426282

mysql select statement not returning rows where some tables in query aren't populated

I'm having a real mind blank - This code selects rows quite nicely apart from those entries where I change st.station_id from a value of '1' to a different (but still valid) number but where there are no entries for that station_id in either the station_owner_map table, the organisation table or the cap_gen_data_table. I basically need to amend my sql to ignore any table where there are no entries.
Select st.station_id, st.station_name , st.st_town, st.st_state, c1.country_name, o1.organisation_name, som1.equity, st.river_basin, st.cost, st.cost_ref, st.comm_year,cg1.caporgen, ht1.hydro_name, cg1.value, srs1.srs_description, cg1.ref_year
FROM station st
inner join station_country_map scm1 on st.station_id = scm1.station_id
inner join country c1 on scm1.country_id = c1.country_id
inner join station_owner_map som1 on st.station_id = som1.station_id
inner join organisation o1 on som1.owner_id = o1.org_id
inner join cap_gen_data cg1 on st.station_id = cg1.station_id
inner join value_lookup vl1 on cg1.caporgen = vl1.id
inner join hydro_type ht1 on cg1.hydro_type_id = ht1.type_id
inner join station_record_status srs1 on cg1.capacity_status = srs1.st_rec_stat_id
where st.station_id = 1
It's caused by your inner joins. Inner join means there has to be a value in both tables for the record to show up in the result set.
Use left join instead, then only the table 'on the left' has to have a value.
Use left join on tables where the value may not be present.
If you have two tables A and B an inner join will only return the rows from A where the join condition is met. A left join will return all rows from A regardless of if the join condition is satisfied. Columns in the select statement associated with B will be null when a left join is used.
I have only added the left join to the tables you have indicated. If other tables may not satisfy the join condition change the join type from inner to left.
Select st.station_id, st.station_name , st.st_town, st.st_state, c1.country_name, o1.organisation_name, som1.equity, st.river_basin, st.cost, st.cost_ref, st.comm_year,cg1.caporgen, ht1.hydro_name, cg1.value, srs1.srs_description, cg1.ref_year
FROM station st
inner join station_country_map scm1 on st.station_id = scm1.station_id
inner join country c1 on scm1.country_id = c1.country_id
left join station_owner_map som1 on st.station_id = som1.station_id
left join organisation o1 on som1.owner_id = o1.org_id
left join cap_gen_data cg1 on st.station_id = cg1.station_id
inner join value_lookup vl1 on cg1.caporgen = vl1.id
inner join hydro_type ht1 on cg1.hydro_type_id = ht1.type_id
inner join station_record_status srs1 on cg1.capacity_status = srs1.st_rec_stat_id
where st.station_id = 1

MySQL `INNER JOIN` multiples of the same table

Is it possible to INNER JOIN a MySQL query to achieve this result?
I have a table with Strategies and a table with Members. The Strategy table holds the ID of the author that corresponds to their ID in the Member table and the ID of an author that updated the existing author's work. Is it possible to grab a reference to both of these people at the same time? Something like the following, which returns no errors, but also no results...
SELECT * FROM Strategies
INNER JOIN Members AS a
INNER JOIN Members AS b
WHERE Strategies.ID='2'
AND Strategies.AuthorID = a.ID
AND Strategies.UpdateAuthorID = b.ID
Use a LEFT JOIN:
SELECT
s.*,
a.Name AS MemberName,
b.Name AS UpdatedMemberName
FROM Strategies AS s
LEFT JOIN Members AS a ON s.AuthorID = a.ID AND s.ID = 2
LEFT JOIN Members AS b ON s.UpdateAuthorID = b.ID AND s.ID = 2 ;
If you want them in one column use COALESCE:
SELECT
s.*,
COALESCE(a.Name, b.Name) AS MemberName
FROM Strategies AS s
LEFT JOIN Members AS a ON s.AuthorID = a.ID AND s.ID = 2
LEFT JOIN Members AS b ON s.UpdateAuthorID = b.ID AND s.ID = 2
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
if domain is table name