Get id details from another table in MYSQL - php

I'm trying to get the value of id from another table
I have a table world_match :
and teams_world:
I'm trying to get the id, date, the name of the home team and away team :
Expected:
id: 1
Date: 25/12/2022
Home: Qatar
Away: Ecuador
So currently, I have a problem with my sql:
SELECT id_match, date_debut, id_domicile, id_exterieur FROM match_world m INNER JOIN teams_world t ON m.id_domicile = t.id_equipe AND m.id_exterieur = t.id_equipe
Someone can explain me my problem in this sql request please ?

I can see what you want to accomplish, but you're going about it the wrong way. You need to join the match_world twice with the teams_world table, once for the home team and once of the away team.
SELECT
match_world.id_match,
match_world.date_debut,
team_home.nom AS home_nom,
team_away.nom AS away_nom
FROM
match_world
INNER JOIN
teams_world AS team_home
ON match_world.id_domicile = team_home.id_equipe
INNER JOIN
teams_world AS team_away
ON match_world.id_exterieur = team_away.id_equipe
You were quite close. Note also that I like to write my queries in a way that they are easy to read, on several line, with indentations, and no abbreviations. This does not impact performance.
(query is untested, no guarantee of functionality given...)

Related

Query selected columns from two tables with a Condition clause

I have two tables-
1) ****Company_Form****
[Contract_No#,Software_Name,Company_Name,Vendor_Code]
2) ****User_Form****
[Contract_No,Invoice_No#,Invoice_Date,Invoice_Amount,Invoice_Submit_Date]
Fields denoted with # and bold are primary keys.
=>The user has to enter a software name for which he wants to get the data of.
=>I have to structure a query in which I have to display the result in the following form:
[Contract#,Software_Name,Company_Name,Invoice_No,Invoice_Date,Invoice_Submission_Date]
Now,
one Contract_No can contain many Invoice_no under its name in
the User Form table.
One Contract_No can occur one time only in
Company_Form table
The retrieved records have to be group by the latest Invoice_Date
I came to the logic that:
I have to first retrieve all the contract numbers with that software
name from Company_Form table.
I have to query that contract number from User_Form table and display
the data for each matched contract no. fetched from Company_Form
table.
The problem is that I am unable to structure a query in SQL that can do the task for me.
Kindly help me in formulating the query.
[PS] I am using SQL with PHP.
I tried a query like:
I tried one approach as :
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.InvoiceSubmitDate
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN(SELECT ContractNo FROM Company_Form WHERE
SoftwareName='$Sname') AND a.ContractNo=b.ContractNo;
But I am getting a error that sub query returns more than 1 row.
Can I get help from this?
I am assuming you are attempting to find the most recent price of the user selected software and its corresponding invoice. Here is an approach to do this. If this is tested to your satisfaction, I can add necessary explanation.
select uf.Contract_No#,
cf.Software_Name,
cf.Company_Name,
uf.Invoice_No#,
uf.Invoice_Date,
uf.Invoice_Amount,
uf.Invoice_Submit_Date
from User_Form uf
inner join (
-- Most recent sale of software
select Contract_No#, max(Invoice_Date)
from User_Form
group by Contract_No#
) latest
on (
-- Filter via join for latest match records
uf.Contract_No# = latest.Contract_No#
and uf.Invoice_Date = latest.Invoice_Date
)
inner join Company_Form cf
on cf.Contract_No# = uf.Contract_No#
where cf.Software_name = :software_name
If the requirement allows your sub query to return more than one row, I would suggest you to use IN instead of = in the where clause of your main query.
Please note that I have just looked at the query and have not fully understood the requirements.
Thanks.
I worked around for some time and finally came to the following query which works like a charm
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.ISD
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN (SELECT ContractNo FROM Company_Form WHERE SoftwareName='$Sname')
AND a.ContractNo=b.ContractNo;
If anybody needs help in understanding the logic of this query,feel free to comment below.

JOIN query too slow on real database, on small one it runs fine

I need help with this mysql query that executes too long or does not execute at all.
(What I am trying to do is a part of more complex problem, where I want to create PHP cron script that will execute few heavy queries and calculate data from the results returned and then use those data to store it in database for further more convenient use. Most likely I will make question here about that process.)
First lets try to solve one of the problems with these heavy queries.
Here is the thing:
I have table: users_bonitet. This table has fields: id, user_id, bonitet, tstamp.
First important note: when I say user, please understand that users are actually companies, not people. So user.id is id of some company, but for some other reasons table that I am using here is called "users".
Three key fields in users_bonitet table are: user_id ( referencing user.id), bonitet ( represents the strength of user, it can have 3 values, 1 - 2 - 3, where 3 is the best ), and tstamp ( stores the time of bonitet insert. Every time when bonitet value changes for some user, new row is inserted with tstamp of that insert and of course new bonitet value.). So basically some user can have bonitet of 1 indicating that he is in bad situation, but after some time it can change to 3 indicating that he is doing great, and time of that change is stored in tstamp.
Now, I will just list other tables that we need to use in query, and then I will explain why. Tables are: user, club, club_offer and club_territories.
Some users ( companies ) are members of a club. Member of the club can have some club offers ( he is representing his products to the people and other club members ) and he is operating on some territory.
What I need to do is to get bonitet value for every club offer ( made by some user who is member of a club ) but only for specific territory with id of 1100000; Since bonitet values are changing over time for each user, that means that I need to get the latest one only. So if some user have bonitet of 1 at 21.01.2012, but later at 26.05.2012 it has changed to 2, I need to get only 2, since that is the current value.
I made an SQL Fiddle with example db schema and query that I am using right now. On this small database, query is working what I want and it is fast, but on real database it is very slow, and sometimes do not execute at all.
See it here: http://sqlfiddle.com/#!9/b0d98/2
My question is: am I using wrong query to get all this data ? I am getting right result but maybe my query is bad and that is why it executes so slow ? How can I speed it up ? I have tried by putting indexes using phpmyadmin, but it didn't help very much.
Here is my query:
SELECT users_bonitet.user_id, users_bonitet.bonitet, users_bonitet.tstamp,
club_offer.id AS offerId, club_offer.rank
FROM users_bonitet
INNER JOIN (
SELECT max( tstamp ) AS lastDate, user_id
FROM users_bonitet
GROUP BY user_id
)lastDate ON users_bonitet.tstamp = lastDate.lastDate
AND users_bonitet.user_id = lastDate.user_id
JOIN users ON users_bonitet.user_id = users.id
JOIN club ON users.id = club.user_id
JOIN club_offer ON club.id = club_offer.club_id
JOIN club_territories ON club.id = club_territories.club_id
WHERE club_territories.territory_id = 1100000
So I am selecting bonitet values for all club offers made by users that are members of a club and operate on territory with an id of 1100000. Important thing is that I am selecting club_offer.id AS offerId, because I need to use that offerId in my application code so I can do some calculations based on bonitet values returned for each offer, and insert data that was calculated to the field "club_offer.rank" for each row with the id of offerId.
Your query looks fine. I suspect your query performance may be improved if you add a compound index to help the subquery that finds the latest entry from users_botinet for each user.
The subquery is:
SELECT max( tstamp ) AS lastDate, user_id
FROM users_bonitet
GROUP BY user_id
If you add (user_id, tstamp) as an index to this table, that subquery can be satisfied with a very efficient loose index scan.
ALTER TABLE users_bonitet ADD KEY maxfinder (user_id, tstamp);
Notice that if this users_botinet table had an autoincrementing id number in it, your subquery could be refactored to use that instead of tstamp. That would eliminate the possibility of duplicates and be even more efficient, because there's a unique id for joining. Like so.
FROM users_botinet
INNER JOIN (
SELECT MAX(id) AS id
FROM users_botinet
GROUP BY user_id
) ubmax ON users_botinet.id = ubmax.id
In this case your compound index would be (user_id, id.
Pro tip: Don't add lots of indexes unless you know you need them. It's a good idea to read up on how indexes can help you. For example. http://use-the-index-luke.com/

Do a TIMESTAMPDIFF for each MySQL row

i have a little problem with a MySQL query, this is my MySQL database structure:
table user
hid(PK)
table request
id (PK), hid, word, time
table click
id, rid (FK),time
i should get the average time between the request and its related click... i've tried this but i'm not sure if it's working properly:
SELECT TIMESTAMPDIFF(SECOND,r.time,c.time)
FROM requests r RIGHT JOIN clicks c ON r.id=c.rid
WHERE r.hid='$hid'
Could someone please tell me if I'm doing it right and explain me why I'm not? I'm getting some numbers as query results, but they don't seem to be right
If you want to get the average time, you forgot to use it in your query (which looks fine besides forgetting "averaging" results).
Try this:
SELECT AVG(TIMESTAMPDIFF(SECOND,r.time,c.time)) as avg_secs_diff
FROM requests r RIGHT JOIN clicks c ON r.id=c.rid
WHERE r.hid='$hid'
GROUP BY r.hid

Beginner SQL - sum with JOIN possibly

I am relatively new to SQL and have only dealt with very basic statements before.
Table A
- id
- clubid
Table B
id
applicationid* (foreign key)id above ^
n
p
k
mg
area
What I am trying to do is as follows,
SELECT * from applications WHERE clubid = $id
Then with the result of this I need to run a query along the lines of,
SELECT Sum(n), Sum(p), Sum(k), Sum(mg) from productsapplied where area = $area
I know this second statement is wrong because it would be sum'ing each row which isnt possible so I am trying to find a way to link the two queries together. As I said I am a beginner with this, I have looked up on Sum as well as inner joins but can't get my head around it.
If more details are needed, let me know! Many thanks !
You need to add a GROUP BY clause to your query.
SELECT applications.id, applications.clubid, sum(products.n), sum(products.p)
FROM applications
JOIN productsapplied AS products
ON productsapplied.applicationid = application.id
GROUP BY application.id
WHERE clubid = $id AND products.area = $area;
Note that you will need to set GROUP BY appropriately. I am assuming that we are summing for each applicationid. I also didn't do every detail of each column as I assume you can figure that out on your own.
I think this may be what you're trying to do:
SELECT Sum(productsapplied.n), Sum(productsapplied.p), Sum(productsapplied.k), Sum(productsapplied.mg)
FROM productsapplied
JOIN applications
ON productsapplied.applicationid = applications.id
WHERE productsapplied.area = $area
AND applications.clubid = $id

Combining two tables different criteria

basically im just trying to finish off a project im working on, having a little trouble finding the right syntax to use for this SQL statement.
Basically what i have two different tables:
Customer:
companyid
companyname
etc etc.
Machine:
machineid
model
serial
companyid
Now usually this would be easy as i would just join the companyid, however, i need to do this slightly differently this time. I need to return specific data from the tables of customer using the customers id to search, and specific data from the tables of machine, using the machine id to search.
Im pretty tired so i do apologise if the answer is staring me straight in the face, but heres what i was working on, again i know its more than likely wrong so i am sorry i have tried searching but to no avail:
$customerquery = mysql_query("
SELECT customer.companyid, customer.companyname,
customer.companyaddress, customer.postcode,
customer.telephone, customer.mobile,
machine.machineid, machine.model,
machine.serial
FROM customer, machine
WHERE customer.companyid=$customerid AND
machine.machineid=$machineid
");
Any help would be greatly appreciated,
Thankyou!
Your current query produces cartesian product since you miss the condition on where the tables should be joined. This is an old syntax of join (SQL-89)
SELECT customer.companyid, customer.companyname,
customer.companyaddress, customer.postcode,
customer.telephone, customer.mobile,
machine.machineid, machine.model,
machine.serial
FROM customer, machine
WHERE customer.companyid = $customerid AND
machine.machineid = $machineid AND
customer.companyid = machine.companyid -- you missed this one producing
-- cartesian product
New syntax of join (SQL-92)
SELECT customer.companyid, customer.companyname,
customer.companyaddress, customer.postcode,
customer.telephone, customer.mobile,
machine.machineid, machine.model,
machine.serial
FROM customer INNER JOIN machine
ON customer.companyid = machine.companyid
WHERE customer.companyid = $customerid AND
machine.machineid = $machineid

Categories