Combining two tables different criteria - php

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

Related

Get id details from another table in MYSQL

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...)

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.

mysqli Table Joining

I’m using Ajax to retrieve information from my database. I have no trouble sending to server PHP and getting information back using simple SQL queries. I came across a section that I needed to pull from 2 tables (Same Database) Both in common are column PO. Attached is a picture of an example.
I have been trying to pull everything from one table that meets my condition like Month of, year of and Store. I have been able to JOIN them but not successfully. Closest I ever got is it checks both tables and only returns the data that have matching PO and not the rest of Table 1.
I like for it to retrieve all rows in table one that meet the conditions and if there is a matching PO in table2 join it else continue to retrieve from table1.
Please any help would be grateful
I figured it out. Thank you
$sql = "SELECT * FROM weekly_report LEFT JOIN tracker ON weekly_report.PO = tracker.POt WHERE MONTH(STR_TO_DATE(`Need By Date (Date)`, '%m-%d-%Y')) = '$month' AND YEAR(STR_TO_DATE(`Need By Date (Date)`, '%m-%d-%Y')) = '$year' AND weekly_report.`Ship To Location (Location ID)` LIKE '%$store%' GROUP BY (weekly_report.PO)";

PHP/SQL Query where tables match (wildcard)

Last time you guys were super helpful, let's hope we can also resolve the following challenge that I'm having.
I have 2 tables in the same database and trying to match fields. Here is the query I'm looking for with the table name however I cannot get it to work:
I want to MATCH table "projects" and Column "categorysecond" table "users_profile" and Column "category".
projects.categorysecond might include example; "Roofing,Windows,Landscaping" and users_profile.category might only have EITHER "Roofing" OR "Windows" OR "Landscaping", so I want to pull the results from "projects" if a result from users_profile.category FITS in projects.categorysecond
***Important - I do not have unique identifiers to do a inner join on example ID. The only match should be on the tables listed above, if words(%Wildcard) from one fits the other.
SAMPLE OF MY ATTEMPT
$sql = "SELECT DISTINCT users_profiles.username, projects.id FROM users_profiles, projects WHERE users_profiles.category like '%' + projects.categorysecond + '%'";
Does this make sense? :)
Thank you in advance.
select distinct
up.username
,p.id
from users_profiles as up
join projects as p
on concat(',',p.categorysecond,',') like concat('%,',up.category,',%')
You have a really bad data format. You should not be storing lists of things in a comma-delimited field. The trouble you are having with this query is just one example of the issues. You cannot get such queries to take advantage of indexes or other optimization techniques.
Sometimes, we are stuck with other people's really bad design decisions. MySQL has the function find_in_set() with works in this case:
SELECT DISTINCT up.username, p.id
FROM users_profiles up JOIN
projects p
ON find_in_set(up.category, p.categorysecond) > 0;
Note: If you don't need the DISTINCT, then don't include it. It just incurs a performance penalty.

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

Categories