Codeigniter - left join tables - mysql

i have a table for my sql like this :
result_podium
id_result_podium
id_race
id_rider
position
point
and
result_dnf
id_result_dnf
id_race
id_rider
So what im trying to do is to join those two table and shown it as one, and here is the result and what i have tried so far :
Attempt 1 :
$this->db->select_sum('result_podium.point');
$this->db->select('riders.name AS rider_name, teams.name AS team_name');
$this->db->from('result_podium');
$this->db->join('riders','riders.id_rider = result_podium.id_rider');
$this->db->join('result_dnf','result_dnf.id_rider = riders.id_rider', 'left');
$this->db->join('teams','teams.id_team = riders.id_team');
$this->db->where('riders.is_deleted','0');
$this->db->order_by("SUM(result_podium.point) DESC");
$this->db->group_by(array('result_podium.id_rider','result_dnf.id_rider'));
$query = $this->db->get();
return $query->result();
And the result is something like this :
No
rider
point
1
Nick
10
2
A
5
3
D
5
4
CC
4
5
B
4
it managed to get data from table result_podium but not managed to join data from table result_dnf, and here is my another attempt :
Attempt 2 :
$this->db->select_sum('result_podium.point');
$this->db->select('result_dnf.*, riders.name AS rider_name, teams.name AS team_name');
$this->db->from('result_dnf');
$this->db->join('riders','riders.id_rider = result_dnf.id_rider');
$this->db->join('teams','teams.id_team = riders.id_team');
$this->db->join('result_podium','result_podium.id_rider = riders.id_rider', 'left');
$this->db->where('riders.is_deleted','0');
$this->db->order_by("SUM(result_podium.point) DESC");
$this->db->group_by(array('result_dnf.id_rider','result_podium.id_rider'));
and here is the result :
No
rider
point
1
A
5
2
D
5
3
B
4
4
CC
4
5
Bri
6
Brum
the point data forBri and Brum, is null because they came from result_dnf, but i did not managed to get Nick data from result_podium.
And here what i was expecting for the data to shown in my view :
No
rider
point
1
Nick
10
2
A
5
3
D
5
4
CC
4
5
B
4
5
Bri
6
Brum
is there a way to join those two table?, anyhelp is really appreciated thank you!.

Related

How with mysql get the same as with php insert...on duplicate key update multiple rows?

For example have such table (named purchase_invoice_items)
Id
NameOfItem
PurchaseQuantity
PurchaseDate
SoldQuantity
1
x
2
2022-04-01
2
y
11
2022-04-01
3
z
8
2022-05-19
4
x
23
2022-08-19
5
x
15
2022-05-19
And i know that sum of sold quantity for NameOfItem x is 20. Sold 20 units of item x. I want to distribute the sold items between PurchaseQuantity using first-in-first-out method. Want to see table like this
Id
NameOfItem
PurchaseQuantity
PurchaseDate
SoldQuantity
1
x
2
2022-04-01
2
2
y
11
2022-04-01
3
z
8
2022-05-19
4
x
23
2022-08-19
3
5
x
15
2022-05-19
15
Using mysql two queries and php, i can do it in following way.
At first i select necessary data from mysql:
$sql_select_purchase_data = 'SELECT `IdPii`, `PurchasedQuantity`
FROM `purchase_invoice_items` WHERE `NameOfItem` = "x"
ORDER BY `PurchaseDate` ASC;';
Then create sql to update.
$sql_update_sold_quantity = 'INSERT INTO `purchase_invoice_items` (`IdPii`, `SoldQuantity`) VALUES ';
php code to continue creating sql
if( isset($arr_select_purchase_data) ){
$sum_of_sold_quantity = 20;
foreach( $arr_select_purchase_data as $one_arr_select_purchase_data ){
if( $sum_of_sold_quantity > 0 ){
$sql_update_sold_quantity .= '(?,?), ';
$data_update_sold_quantity[] = $one_arr_select_purchase_data['IdPii'];//For 'IdPii'
$data_update_sold_quantity[] = min( $one_arr_select_purchase_data['PurchasedQuantity'], $sum_of_sold_quantity);//For 'SoldQuantity'
$sum_of_sold_quantity = $sum_of_sold_quantity - min( $one_arr_select_purchase_data['PurchasedQuantity'], $sum_of_sold_quantity);
}//if( $sum_of_sold_quantity > 0 ){
else{ break; }
}//foreach(
$sql_update_sold_quantity = rtrim(trim($sql_update_sold_quantity), ','). ' ON DUPLICATE KEY UPDATE `SoldQuantity`= VALUES(`SoldQuantity`);';
But this is waste of resources (if i need to select-update many rows)? Two mysql queries and additionally php code.
Any ideas how can i get the same using only mysql (one mysql query; without php)?

sql - get parentID with or without child in self refrenced table

Here is my table's (events) content. eventID is "primary key" and parentID is "foreign key" with references to events(eventsID)
self referenced table :
eventID eventName parentID appFK
1 evt1 null 2
2 evt2 1 1
3 evt3 1 1
4 evt4 null 3
5 evt5 8 3
6 evt6 null 4
7 evt7 null 1
8 evt8 null 1
and another table content (applications) like this :
appID appName
1 app1
2 app2
3 app3
4 app4
I'd like to fetch all eventIDs which are parents or not with a given appID. If a child has the given appID, i'd like to get his parentID and not himself. So the result is going to be like this with appID = 1 :
eventID eventName ParentID appFK
1 evt1 null 2 // parent event who has children with appID = 1
7 evt7 null 1 // event with no child and appID = 1
8 evt8 null 1 // parent event with appID = 1 and has a child
I tried lot of examples and read a lot of solutions here but i didn't find a problem like this. Can you help me to write the right SQL ?
thx.
Try this:
SELECT DISTINCT COALESCE(e2.eventID, e1.eventID),
COALESCE(e2.eventName, e1.eventName),
COALESCE(e2.appFK, e1.appFK)
FROM events AS e1
LEFT JOIN events AS e2 ON e1.parentID = e2.eventID AND e1.appFK = 1
WHERE (e1.appFK = 1 AND e1.parentID IS NULL) OR (e2.eventID IS NOT NULL)
The LEFT JOIN fetches parent records (e1.parentID = e2.eventID) of a child having appID = 1 (e1.appFK = 1).
The WHERE clause selects root records having appID = 1 and root records that are related to a child having appID = 1 (e2.eventID IS NOT NULL).
Demo here

Join two Tables Only on First Set of Values

Table 1 : Anamoly
id Source
1 dls
2 aus
3 dls
4 aus
Table 2 : Logical_Mapping
Source Destination minValue
dls hst 1
aus hst 2
dls buf 1
aus buf 2
Expected Output
Anomaly-Mapping
id Source Destination minValue
1 dls hst(or)buf 1
2 aus hst(or)buf 2
3 dls hst(or)buf 1
4 aus hst(or)buf 2
The 'minValue' is dependent on the source and not the 'destination'.
The query I tried was :
select an.id,an.Source, (select l.Destination from logical_mapping as l where an.Source= l.Source limit 1) as Dest from anomaly;
The query seems to work fine. But I need 'minValue' also along with 'Destination'.
Try this:
SELECT an.id, an.source, l.destination, l.minValue
FROM anamoly an
LEFT JOIN logical_mapping l ON l.source=an.source

get greatest Id from multiple table and remove duplicate value

i got some problem obtaining value from my db,this is my first db
ID_HARGA ID_USER ID_BAG_PEMASARAN ID_ITEM HARGA ENTRY_DATE
1 9 1 3 1000000 2015-01-11 09:55:27
2 9 1 5 2000000 2015-01-13 07:19:10
5 9 1 3 3000000 2015-01-13 13:47:32
6 9 1 43 7000000 2015-01-13 13:49:49
13 9 1 50 3000000 2015-01-13 17:56:54
37 9 1 50 100 2015-01-19 09:08:20
this is the second one
ID_ITEM NAMA_ITEM SPEC_ITEM MASA_GARANSI STATUS_ITEM DIR_IMAGE
3 water heater emas bagus sekali selamanya 1
5 water heater tembaga bagus super selamanya 1
43 water hater heater seupo 3 1 water_22.jpg
50 tankkk 50 Liter 1 1 water_2.jpg
i know there is some null value just igniore it, i already did this
public function get_item()
{
//menghitung jumlah varian barang yang ada
$querycounter = $this->db->query('select * from ITEM WHERE STATUS_ITEM = 1');
$counter = $querycounter->num_rows();
$this->db->select('ITEM.ID_ITEM,NAMA_ITEM,SPEC_ITEM,HARGA,DIR_IMAGE');
$this->db->from('ITEM');
$this->db->join('HARGA', 'ITEM.ID_ITEM = HARGA.ID_ITEM','left');
// $this->db->order_by('ENTRY_DATE','DESC');
//$this->db->limit($counter);
$this->db->where('STATUS_ITEM',1);
//$query = $this->db->query('select from ITEM i join HARGA h on i.ID_ITEM = h.ID_ITEM order by h.ENTRY_DATE ASC');
$query = $this->db->get();
return $query->result_array();
//$this->db->select('nama_item','spec_item');
//$query = $this->db->get('item');
}
what i want is,just ignore dir_image
ID_ITEM NAMA_ITEM HARGA DIR_IMAGE
3 water heater emas 1000000
5 water heater tembaga 3000000
43 water hater 7000000
50 tankk 100
ID_item with biggest number not the old , so everytime i am insert into id_harga with ID_ITEM
the result always the newest HARGA
Thx before
There is a little confession that, do you want to get the maximum hagra, or newest inserted data (identifiable by HAGRA_ID if its auto increment by 1) in Hagra table. Your Code should be like
$this->db->select('ITEM.ID_ITEM,NAMA_ITEM,SPEC_ITEM,max(HARGA),DIR_IMAGE');
$this->db->from('ITEM');
$this->db->join('HARGA', 'ITEM.ID_ITEM = HARGA.ID_ITEM','left');
$this->db->where('STATUS_ITEM',1);
$this->db->group_by('item.item_id');
This will join your tables and select maximum value of Hagra. To use Max function, you need to use group_by(CodeIgniter Documentation) clause, other wise it will show only the single maximum value. Group_by will help to show maximum value of each group (each item);
If you want to get the newest inserted data, you can use the same technique using
$this->db->select('MAX(HAGRA_ID),ITEM.ID_ITEM,NAMA_ITEM,SPEC_ITEM,HARGA,DIR_IMAGE');

how to select/add a column to pandas dataframe based on a non trivial function of other columns

This is a followup question for this one: how to select/add a column to pandas dataframe based on a function of other columns?
have a data frame and I want to select the rows that match some criteria. The criteria is a function of values of other columns and some additional values.
Here is a toy example:
>> df = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],
'B': [randint(1,9) for x in xrange(9)],
'C': [4,10,3,5,4,5,3,7,1]})
>>
A B C
0 1 6 4
1 2 8 10
2 3 8 3
3 4 4 5
4 5 2 4
5 6 1 5
6 7 1 3
7 8 2 7
8 9 8 1
I want select all rows for which some non trivial function returns true, e.g. f(a,c,L), where L is a list of lists and f returns True iff a and c are not part of the same sublist.
That is, if L = [[1,2,3],[4,2,10],[8,7,5,6,9]] I want to get:
A B C
0 1 6 4
3 4 4 5
4 5 2 4
6 7 1 3
8 9 8 1
Thanks!
Here is a VERY VERY hacky and non-elegant solution. As another disclaimer, since your question doesn't state what you want to do if a number in the column is in none of the sub lists this code doesn't handle that in any real way besides any default functionality within isin().
import pandas as pd
df = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],
'B': [6,8,8,4,2,1,1,2,8],
'C': [4,10,3,5,4,5,3,7,1]})
L = [[1,2,3],[4,2,10],[8,7,5,6,9]]
df['passed1'] = df['A'].isin(L[0])
df['passed2'] = df['C'].isin(L[0])
df['1&2'] = (df['passed1'] ^ df['passed2'])
df['passed4'] = df['A'].isin(L[1])
df['passed5'] = df['C'].isin(L[1])
df['4&5'] = (df['passed4'] ^ df['passed5'])
df['passed7'] = df['A'].isin(L[2])
df['passed8'] = df['C'].isin(L[2])
df['7&8'] = (df['passed7'] ^ df['passed8'])
df['PASSED'] = df['1&2'] & df['4&5'] ^ df['7&8']
del df['passed1'], df['passed2'], df['1&2'], df['passed4'], df['passed5'], df['4&5'], df['passed7'], df['passed8'], df['7&8']
df = df[df['PASSED'] == True]
del df['PASSED']
With an output that looks like:
A B C
0 1 6 4
3 4 4 5
4 5 2 4
6 7 1 3
8 9 8 1
I implemented this rather quickly hence the utter and complete ugliness of this code, but I believe you can refactor it any way you would like (e.g. iterate over the original set of lists with for sub_list in L, improve variable names, come up with a better solution, etc).
Hope this helps. Oh, and did I mention this was hacky and not very good code? Because it is.