selecting most recent row from joined table in MySQL - mysql

I have two tables, Project and Projectnote
There is a one to many relationship between project and projectnote.
I want to be able to list my projects and select the most recent projectnotes based on the id.
Is this possible to do in Mysql query, I can't figure it out.
Thanks for any help!
Edit: so far I have a basic query (below) that joins the two tables. However, this only selects projects where a note exists and I get multiple rows where there are several notes per project.
SELECT `driver_checkins`.*, `driver_trips`.`id` AS `trip_id`, `driver_trips`.`trip_num` AS `trip_num`, `driver_trips`.`status` AS `trip_status`, `driver_trips`.`ride_date` AS `ride_date`, `driver_trips`.`today_date` AS `trip_today_date`, `driver_trips`.`pick_up_time` AS `pick_up_time`, `driver_trips`.`d_time` AS `d_time`, `driver_trips`.`trip_type` AS `trip_type`
FROM `driver_checkins`
LEFT JOIN `driver_trips` ON `driver_trips`.`driver_id` = `driver_checkins`.`driver_id` WHERE `checkin_status` = 1 AND `booking_status` = 0;

Using a GROUP BY clause and the GROUP_CONCAT function should do the trick.
I am assuming that "driver_checkins" is your "Project" table and "driver_trips" is your "Projectnote" table.
SELECT `driver_checkins`.*, GROUP_CONCAT(`driver_trips`.`id`, `driver_trips`.`status` ORDER BY `driver_trips`.id DESC SEPARATOR " --- " LIMIT 3)
FROM `driver_checkins`
LEFT JOIN `driver_trips` ON `driver_trips`.`driver_id` = `driver_checkins`.`driver_id`
WHERE `checkin_status` = 1 AND `booking_status` = 0
GROUP BY `driver_checkins`.id;
This should display id and status for the last 3 driver_trips per driver_checkin, separated by " --- ".
Something to consider: while in many cases ordering by id will work chronologically, it's always better to add a timestamp column (e.g. called created) instead to order by chronologically.

Related

Select data from table using SQL query

I have a table name "chat_details" I wanna access only data with green underline according to time, I use the following query
//suppose $user_id = 1;
"SELECT *
FROM chat_details WHERE from_user_id='$user_id' OR to_user_id='$user_id' ORDER BY time DESC"
It fetch all the rows because all rows contain user_id = 1 in one of the column, but i need only green underline rows as compare to red one because green one are latest according to time(column), how can i fetch only these green underlines?
This is one posible query, that should solve your question.
SELECT *
FROM chat_details c
WHERE (c.from_user_id='$user_id' OR c.to_user_id='$user_id')
AND NOT EXISTS (
SELECT 1 FROM chat_details d
WHERE d.from_user_id = c.from_user_id
AND d.to_user_id = c.to_user_id
AND d.time > c.time)
ORDER BY c.time DESC"
Actually I could not test, hope I haven't made a mistake.
The query selects all data as in your query, but only thoose which haven't a newer chat between the two users.
For the EXISTS keyword see http://www.mysqltutorial.org/mysql-exists/

ID lost after left join on table

Hey I tried this thread but it doesn't work and i can't figure out why...
here's my SQL:
SELECT * FROM gone_items
LEFT JOIN items
ON gone_items.item_ID=items.ID
WHERE
gone_items.aus_ID='$ID'
ORDER BY items.name ASC
Now, I fetch that via PHP and have a $row and try another mysql to get the individual ID's of the gone_items table. But if i use $row['ID'] I get the ID of the items.ID not the one from gone_items.ID.
I tried setting the variable manually in the first query but it doesn't work.
I also tried this: MYSQL Left join A.table and b.table while retaining a.table id
Also didn't help me...
All I want is to retain the ID (Primary key) from the gone_items table..
Can anyone please tell me what I'm doing wrong ?
Love
Gram
EDIT
//Query for Joined infos
$sqlx="SELECT foto_res_ausgeliehene_geg.ID, foto_res_ausgeliehene_geg.aus_ID, foto_res_ausgeliehene_geg.geg_ID, foto_res_ausgeliehene_geg.zusaetzliches, foto_res_gegenstaende.ID, foto_res_gegenstaende.bezeichnung, foto_res_gegenstaende.seriennummer, foto_res_gegenstaende.interne_seriennummer, foto_res_gegenstaende.zusaetzliches FROM foto_res_ausgeliehene_geg
LEFT JOIN foto_res_gegenstaende
ON foto_res_ausgeliehene_geg.geg_ID=foto_res_gegenstaende.ID
WHERE
foto_res_ausgeliehene_geg.aus_ID='$ID'
ORDER BY foto_res_gegenstaende.bezeichnung ASC
";
$ergebnisx = mysqli_query($db,$sqlx);
while ($zeilex = mysqli_fetch_assoc($ergebnisx))
{
//Query for individual infos
$sqly="SELECT * FROM foto_res_ausgeliehene_geg
WHERE `geg_ID`='".$zeilex['ID']."'
AND `aus_ID`='$ID'
GROUP BY `geg_ID`
";
$ergebnisy = mysqli_query($db,$sqly);
while ($zeiley = mysqli_fetch_assoc($ergebnisy))
{};
Now I did select all items individually. The foto_res_ausgeliehene_geg.ID still merges with the foto_res_gegenstanede.ID due to the LEFT JOIN.
So if i access $zeilex['ID'] im getting the ID of foto_res_gegenstaende.ID.
Would it help if I rename the ID field in one of the tables into lets say item_ID ?
Thanks alot.
Love
Gram.
Instead of using select *, you should explicitly state what items you want to select. Else you can get conflicts with multiple id fields. In your case something like:
select gone_items.id, gone_items.column1, gone_items.column2, items.column1, items.column2
It is also considered good practice, to limit the amount of data there is being selected. But is meanwhile also a highly debateable what is the right way. Performance issue in using SELECT *?
WORKS!
I simply renamed one of the Primary ID keys to something else, in this case, one of them got ID -> item_ID. The other one still is ID that way the left join won't merge them.
yolo
EDIT
WORKING CODE
$sqlx="SELECT foto_res_ausgeliehene_geg.item_ID, foto_res_ausgeliehene_geg.aus_ID, foto_res_ausgeliehene_geg.geg_ID, foto_res_ausgeliehene_geg.zusaetzliches, foto_res_gegenstaende.ID, foto_res_gegenstaende.bezeichnung, foto_res_gegenstaende.seriennummer, foto_res_gegenstaende.interne_seriennummer, foto_res_gegenstaende.zusaetzliches FROM foto_res_ausgeliehene_geg
LEFT JOIN foto_res_gegenstaende
ON foto_res_ausgeliehene_geg.geg_ID=foto_res_gegenstaende.ID
WHERE
foto_res_ausgeliehene_geg.aus_ID='$ID'
ORDER BY foto_res_gegenstaende.bezeichnung ASC
";
$ergebnisx = mysqli_query($db,$sqlx);
while ($zeilex = mysqli_fetch_assoc($ergebnisx))
{
//Query for individual infos
$sqly="SELECT * FROM foto_res_ausgeliehene_geg
WHERE `item_ID`='".$zeilex['item_ID']."'
";
$ergebnisy = mysqli_query($db,$sqly);
while ($zeiley = mysqli_fetch_assoc($ergebnisy))
{

SQL Query Assistance - Left join unexpected result

I have these 2 queries:
$sql = "SELECT *
FROM ultrait_wpl_properties
LEFT JOIN ultrait_wpl_property_types
ON ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id ";
$sql2 = "SELECT *
FROM ultrait_wpl_properties, ultrait_wpl_property_types
WHERE ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id";
For some odd reason when the IDs are output some are duplicated? By my reseaning these queries should get everything from the table in the first part and join the second table based on the WHERE condition.
<property><id>13</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>7</id></property>
This may be slightly unclear but for some reason I'm getting duplicate IDs, all i want really is to be able to access the property type which links to the ID in the second table.
I have tested both queries in phpMyAdmin and they yeild the desired result, however when I use the queries in my php script they return unexpected results.
You are getting one row for each row in table ultrait_wpl_properties. What else do you expect? If it is just one record per type, then you would have to re-write your query accordingly. You select * from both tables. But is it only the type ID you need? Then why join the tables at all?
Get all type IDs:
select id from ultrait_wpl_property_types;
Get all type IDs in table ultrait_wpl_properties:
select distinct property_type from ultrait_wpl_properties;
Get all type data for types in ultrait_wpl_properties:
select * from ultrait_wpl_property_types
where id in (select property_type from ultrait_wpl_properties);
You are getting a Cartesian result in the case the ultrait_wpl_property_types table has multiple records for a single property. Such as a property type could be Type A, Type B, Type C which might be descriptive "types". So a single property would be accounted for each entry.
You might just need to do SELECT DISTINCT, or GROUP BY ultrait_wpl_properties.id to make sure only one record per ID, but with generic "Select * ", I would first try with GROUP BY.

how to perform a table join when the other table has many rows corresponding to one row in mother table

I have two table --> tbl_book_details and tbl_table_traking
tbl_book_details has columns bd_book_code,
bd_isbn,
bd_title,
bd_edition,
bd_author,
bd_publisher,
bd_supplier,
bd_page,
bd_price_type,
bd_cost_price,
bd_price,
bd_Tax,
bd_covering,
bd_availability,
bd_keywords,
bd_notes,
bd_details,
bd_news_latter,
bd_etDate,
bd_weight,
bd_expire_date,
bd_status
tbl_table_traking has columns
tt_id,
tt_action,
tt_table,
tt_record_id,
tt_on_date,
tt_user,
tt_status
the process is a trigger is defined on tbl_book_details which in case of insert/modify insert the data in tbl_table_traking for traking when and who has modified the records.
till now i have been using following query which is not a join -->
SELECT
tbl_books_details.bd_book_code AS bkid,
tbl_books_details.bd_isbn,
tbl_books_details.bd_title AS title,
-- This part is what I believe is slowing down my query
(SELECT
tt_on_date
FROM
tbl_table_tracking
WHERE tt_action = 'MODIFY'
AND tt_record_id = tbl_books_details.bd_book_code ORDER BY tt_on_date) AS bd_etdate
it was working fine when the records count were below 3 million, but now script time out is occurring.
I have made the index on tbl_table_traking on 'tt_ondate' and on tt_action,
If there any way i can convert it to a join or improve the performance?
the table traking query is returning the mostrecent date on which the record was modified.
my database is in mysql.
You should be able to do something like this.
SELECT
tbl_books_details.bd_book_code AS bkid,
tbl_books_details.bd_isbn,
tbl_books_details.bd_title AS title,
tbl_table_traking.tt_on_date
FROM
tbl_books_details
INNER JOIN tbl_table_tracking
tbl_books_details.bd_book_code = tbl_table_tracking.tt_record_id
WHERE tt_action = 'MODIFY';
Hope this helps...

Why this Query takes such a long time to execute

I have three tables
glSalesJournal
HMISAdd
HMISMain
Now what i am trying to do is add the glSalesJournal amt with HMISAdd amt while grouping up with various Fields and inserting the result into glSalesJournal
The glSalesJournal contains 633173 records
The HMISAdd contains 4193 records
HMISAdd and glSalesJournal contains the same columns which are
loc
glAcct
glSubAcct
batchNbr
contractNbr
amt
I added indexes to the table still the results are the same.
Here is my code:
INSERT INTO hmismain
(loc,
glacct,
subacct,
batchnbr,
contractnbr,
amt)
SELECT glsalesjournal.loc,
glsalesjournal.glacct,
glsalesjournal.glsubacct,
( glsalesjournal.amt + hmisadd.amt ) AS sumAmt,
glsalesjournal.batchnbr,
glsalesjournal.salescontnbr
FROM glsalesjournal
LEFT OUTER JOIN hmisadd
ON ( glsalesjournal.loc = hmisadd.loc
AND glsalesjournal.glacct = hmisadd.glacct
AND glsalesjournal.glsubacct = hmisadd.subacct
AND glsalesjournal.batchnbr = hmisadd.batchnbr
AND glsalesjournal.salescontnbr = hmisadd.contractnbr )
GROUP BY glsalesjournal.loc,
hmisadd.loc,
glsalesjournal.glacct,
hmisadd.glacct,
glsalesjournal.glsubacct,
hmisadd.subacct,
glsalesjournal.batchnbr,
hmisadd.batchnbr,
glsalesjournal.salescontnbr,
hmisadd.contractnbr
The time taken by the script to execute is more than 2 hours. Even when I limit the Records to 100 the time taken is the same.
Can someone please guide me how can I optimize the script.
Thanks
1) It looks like it's a one off query, am I correct here? If not than you are inserting the same data into hmismain table every time.
2) You are grouping on fields from TWO separate tables, so no amount of indexing will ever help you. The ONLY index that will help is an index over a view linking these two tables in the same way.
Further note:
What is the point of
GROUP BY glsalesjournal.loc,
hmisadd.loc,
glsalesjournal.glacct,
hmisadd.glacct,
glsalesjournal.glsubacct,
hmisadd.subacct,
glsalesjournal.batchnbr,
hmisadd.batchnbr,
glsalesjournal.salescontnbr,
hmisadd.contractnbr
You are grouping the data by the same fields twice
glsalesjournal.loc, hmisadd.loc
glsalesjournal.glacct, hmisadd.glacct,
...
Remove the duplicates from GROUP BY and it should run fast
Did you add an index on this fields:
glSalesJournal.loc
glSalesJournal.glAcct
glSalesJournal.glSubAcct
glSalesJournal.batchNbr
glSalesJournal.salesContNbr
HMISAdd.Loc
HMISAdd.GlAcct
HMISAdd.SubAcct
HMISAdd.batchNbr
HMISAdd.contractNbr
If this fields are unindexed, it will perform fulltable scan for each individual record thus causing slow performance.
MySQL Create Index Syntax