How to join tow times the same table? - mysql

I need to join twice the same table how do a do it in Codeigniter?
TABLE MATCH
match_id
team_home_id
team_away_id
score_home
score_away
group_id
round_id
winner
start_date
start_time
TABLE TEAM
team_id
name
code
This are the two tables I have to join. The table team has to join twice with a table match.
$this->db->select('*')
->from('match, team')
->join('team AS team_a', 'match.team_home_id = team_a.team_id')
->join('team AS team_b', 'match.team_away_id = team_b.team_id')
->get()->result();
My result is the match and just one of the teams :/

Thank you, Strawberry for your help.
On my query, I was getting always the last team joined because it looks like Codeigniter overwrites the columns with the same name, team_a.name and team_a.code are represented in the final result_array() as array key "name" and "code" the same as team_b.name and team_b.code.
So more than an alias for the tables I needed to add an alias for the columns:
$this->db->select('tips.stake, tips.odd,
matches.score_home, matches.score_away, matches.winner, matches.start_date, matches.start_time,
team_home.name AS team_home_name, team_home.code AS team_home_code, team_away.name AS team_away_name, team_away.code AS team_away_code');
$this->db->from('tips');
$this->db->join('matches', 'matches.match_id = tips.match_id');
$this->db->join('`teams` `team_home`', 'team_home.team_id = matches.team_home_id');
$this->db->join('`teams` `team_away`', 'team_away.team_id = matches.team_away_id');
$query = $this->db->get();

Related

Access or Mysql - Table rows as columns in query

I have these three tables:
The table "Clienti" contains the customers.
The table "Corsi" contains all the available courses
The table "corsi Fatti" contains all the Courses each client has taken.
what I would need is a query that returns each client, and what courses he attended on what date.
For that I would like to have for example a table returned with these columns:
Clienti.Nome, corsi.row1.corso, corsi.row2.corso, corsi.row3.corso,corsi.rowN.corso.
and the content of the table should be:
clienti.Nome, corsifatti.data of the matching course in the corsi table if present.
so, first column is the client name, and then there is a column for each row of the "corsi" table, and if a client has partecipated on that course then the corsifatti.data should be in that column.
Can something like this be done with a Access or Mysql Query? I have tried with inner joins but the result was not what I need.
select
Clienti.nome, Clienti.Addresse, Clienti.CAP, Clienti.Tel,
Clienti.Ansprechpartner, Clienti.Mail, Clienti.Weiteres,
CorsiFatti.Data, Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
What you are asking is a simple inner join:
select Clienti.nome, Clienti.Addresse, Clienti.CAP,
Clienti.Tel, Clienti.Ansprechpartner, Clienti.Mail,
Clienti.Weiteres,
CorsiFatti.Data,
Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
order by Clienti.nome, Corsi.Corso;
I think you meant yours was lacking the order by only.
I wouldn't suggest using access, but if it is access anyway, then you need to have parenthseses around all those joins (peculiar I know, but it is access).
The pivot with variable columns count is complicated. I can advice simplest solution uses JSON aggregation:
SELECT
ClienteId,
Name,
JSON_ARRAYAGG(
JSON_OBJECT("Data", Data, "Corso", Corso)
) Corsi
FROM
CorsiFatti
JOIN Corsi ON Corsi.Id = CorsiFatti.CorsoId
JOIN Clienti ON Clienti.Id = CorsiFatti.clienteId
GROUP BY
ClienteId,
Name
;
Result is row for each client contains client's data at his courses as JSON string:
+===========+=========+========================================================================================+
| ClienteId | Name | Corsi |
+===========+=========+========================================================================================+
| 1 | Mr. Fix | [{"Data": "2021-01-01", "Corso": "Corso1"}, {"Data": "2021-02-01", "Corso": "Corso3"}] |
+-----------+---------+----------------------------------------------------------------------------------------+
Here you can find SQL fiddle

How to write sql query for the following tables

I have a table name as "invoice" which consists of column name "CId"
I have another table name as invoiceclient_details which consists of column name "CId"
So now my question is "what query should i write so that i will get the data of greater "CId" i.e. rows of data which consists of greater "CID"
I have tried like this
SELECT
invoiceclient_details.OrganizationName,
invoiceclient_details.InvoiceNo,
invoiceclient_details.InvoiceDate,
invoiceclient_details.DeliveryNote,
invoiceclient_details.TermsofPayment,
invoiceclient_details.EsugamNo,
invoiceclient_details.OrganizationName,
invoiceclient_details.BuyerOrderNo,
invoiceclient_details.BuyDate,
invoiceclient_details.DispatchDocumentNo,
invoiceclient_details.Dated,
invoiceclient_details.DispatchThrough,
invoiceclient_details.Destination,
invoiceclient_details.TermsofDelivery,
invoiceclient_details.BuyerTin,
invoice.id,
invoice.DescriptionOfGoods,
invoice.Quantity,
invoice.PerUnitPrice,
invoice.TotalPrice,
invoice.VAT14,
invoice.VAT5,
invoice.ServiceTax,
invoice.CST
FROM invoiceclient_details,invoice
WHERE MAX(invoiceclient_details.CId) = MAX(invoice.CId);
But it is showing an error like
"misusage of group function"
Use an INNER JOIN to join the tables on the CId.
SELECT *
FROM invoice i
INNER JOIN invoiceclient_details icd ON i.CId = icd.CId
Try this
select *
from invoice,invoiceclient_details
where
invoice.CId in (Select max(invoiceclient_details.CId) from invoiceclient_details)
and
invoiceclient_details.CId in (Select max(invoiceclient_details.CId) from invoiceclient_details)

mysql regex not returning correct results

I have a table called lis_pendens and a table called docket_entries. Each lis_pendens record has many docket_entries, where the foreign key of docket_entries is case_id. If the description field of docket_entries contains the text 'writ' or 'title' or 'sale' or 'dismissal', then I do not want to return the associated lis_penden record in the result set. Otherwise, if none of the docket_entries belonging to a lis_pendnes record contain these keywords, then I want to return the lis_pendens record in the result set.
Here is the query I have created:
SELECT lis_pendens.id as id
FROM lis_pendens
INNER JOIN docket_entries
ON docket_entries.case_id = lis_pendens.id
WHERE no_foreclosure_sale_created_at IS NULL
AND NOT EXISTS (
SELECT 1 FROM docket_entries AS e
WHERE e.case_id = lis_pendens.id
AND LOWER(e.description) REGEXP 'writ|title|sale|dismissal'
) GROUP BY id
I thought the query was good but it's producing EVERY lis_pendens record in the database, even though some of those lis_pendens records have associating docket_entries whose description field contains this:
Notice of Voluntary Dismissal
Notice of Dismissal & Discharge of Lis Pendens
Certificate of Title
...
Obviously, something is wrong with the query. What am I doing wrong?
You could use MAX() to perform a group-wise NAND operation:
SELECT p.id
FROM lis_pendens p
INNER JOIN docket_entries e ON e.case_id = p.id
GROUP BY p.id
HAVING MAX(LOWER(e.description) REGEXP 'writ|title|sale|dismissal') = 0;

mysql - Order by from multiple tables in Laravel

I have 3 tables topic1, topic2, topic3. I split into 3 tables because of huge difference in attributes. all of these table has a common column of created_timestamp
I would like to create a timeline displaying from the latest with the created_timestamp as reference.
I have tried joining the tables and order by greatest (t1.created_timestamp, t2.created_timestamp, t3.created_timestamp) but I can't do this in the query builder of laravel.
Plus when displaying of the attributes, they will be repeated, is there a way to only show topic1 attributes if topic1 is the latest, so on and so forth.
Or is there a better method?
Thank you Jedi masters!
I forgot to mention about a fourth table (follower table) that only shows the created_by of the 3 topic tables.
topic1 {var1, var2, created_timestamp, user_id)
topic2 {var3, var2, var3, created_timestamp, teacher_id)
topic3 {var3, created_timestamp, visitor_id)
follower {follow_id, creator_id}
follow_id = user_id, teacher_id, visitor_id (table joins)
I would need to get only rows that I follow (aka where follower.creator_id = $me)
I think the best way would be to run a query for each table and then combine the results.
$a = DB::table('topic1')->join('follower', 'folower.follow_id', '=', 'topic1.user_id')->where('folower.follower_id', $followed)->get();
$b = DB::table('topic2')->join('follower', 'folower.follow_id', '=', 'topic2.teacher_id')->where('folower.follower_id', $followed)->get();
$c = DB::table('topic3')->join('follower', 'folower.follow_id', '=', 'topic3.visitor_id')->where('folower.follower_id', $followed)->get();
$results = new Illuminate\Database\Eloquent\Collection;
$results = $results->merge($a)->merge($b)->merge($c)->sortBy('created_timestamp');

need assistance on constructing sql query

i have three tables like follows:
this one table : m_application_resources
resourceid resource_name menu_group_id menu_name creation_date last_created_by updation_date last_updated_by
and the second table : m_roles
roleid rolename description creation_date last_created_by updation_date last_updated_by
and the third table is : m_access_matrix
accessid resourceid roleid creation_date last_created_by updation_date last_updated_by
Relationship for the table is : resourceid and roleid
and this my query
select am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am
where ar.resourceid=am.resourceid
this returns the following :
ccessid resource_name rolename
1 DepartmentAction Admin
1 DepartmentAction Client
1 DepartmentAction Doctors
2 PositionsAction Admin
2 PositionsAction Client
2 PositionsAction Doctor
the result is wrong and i don't know how to go about.
Ex : DepartmentAction should come only once and the role name should be any one.
SqlfiddleFiddle
Please help
You do not have a condition on role_id:
select am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am
where ar.resourceid=am.resourceid AND am.roleid = rls.roleid
I would convert the query to ANSI SQL syntax for joins for better clarity:
SELECT am.accessid, ar.resource_name,rls.rolename
FROM m_application_resources ar
JOIN m_access_matrix am ON ar.resourceid=am.resourceid
JOIN m_roles rls ON am.roleid = rls.roleid
It would be best to explicitly join the tables in your query. I'm not 100% sure I understand your tables, but this should work:
SELECT am.accessid, ar.resource_name, rls.rolename
FROM (m_application_resources ar INNER JOIN m_access_matrix am
ON ar.resourceid = am.resourceid) INNER JOIN mroles rls ON am.roleid = rls.roleid