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
Related
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...)
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.
I think the title is quite straightforward but basically I have 2 mysql tables that hold various information. Linking them together is a unique id.
One of the tables is showing a total of 2 rows less than the other. I would like to run through these rows and find out which id values are missing. I do not know enough of mysql to say that this is not possible using only mysql but i thought it would be an easier task with php.
so something like this which really is a thumbsuck :
if ($stmt = $link->prepare("
SELECT i.id AS itemsId, c.item_id AS catsId
FROM items i
INNER JOIN item_categories c
WHERE i.id = c.item_id
"))
{
$stmt->execute();
$stmt->bind_result($id1, $id2);
$stmt->close();
}
while ($stmt->fetch())
{
*run through the numbers and echo which numbers are missing out of 1 to 300.*
}
Would anyone have any idea on how i could accomplish something like this?
Any advice, suggestion or information would be greatly appreciated, thank you!
SELECT id FROM items WHERE id NOT IN (SELECT item_id FROM item_categories);
I've asked a question regarding my SQL Query a while back and it worked fine until I noticed I had forgotten a very important piece to the code and now I've spent about an hour and a half trying to modify my code. The original question asked a good way to inner join two tables (orders and order_items). I then did a mysql_num_row() over the SQL Query and called it a day. I forgot that there's a cell in my order_items table named quantity. I need to integrate this into my count. I'm including my code below, and any ideas on how to easily implement this would be appreciated.
$SQL2ORDERSEARCH = "
SELECT * FROM order_items
INNER JOIN orders
ON orders.id = order_items.ord
WHERE orders.session = '$sessionID'
AND order_items.dish = '$SEARCHITEMS_OBJECT->dish'
AND order_items.size = 'full'";
$ORDERSEARCH = mysql_query($SQL2ORDERSEARCH) or die(mysql_error());
$ORDERSEARCH_NUM_ROWS = mysql_num_rows($ORDERSEARCH);
$FULLTOTAL = $FULLTOTAL + $ORDERSEARCH_NUM_ROWS;
I tried attempting a different route by doing a count. So I modified my Query as such:
$SQL2ORDERSEARCH = "
SELECT COUNT(quantity) FROM order_items
INNER JOIN orders
ON orders.id = order_items.ord
WHERE orders.session = '$sessionID'
AND order_items.dish = '$SEARCHITEMS_OBJECT->dish'
AND order_items.size = 'full'";
I don't technically need anything else since all I am trying to do is count how many dishes are involved here. I then created an if statement to figure if there was any rows coming from this query, and then calculate the quantity of them.
if($ORDERSEARCH_NUM_ROWS > 0 ) {
while($ORDERSEARCH_OBJECT = mysql_fetch_object($ORDERSEARCH)) {
$FULLQTY = COUNT($ORDERSEARCH_OBJECT->quantity);
}
}
I've gotten mixed results. Sometimes I get just straight 1's down the data table. Other times (depending on any small changes such as $FULLQTY += COUNT($ORDERSEARCH_OBJECT->quantity); and trying that) I get results where it seems almost pattern-like with the numbers increasing by 5+ and somehow adding up to near 20+ the further down the list you go.
I'm just looking for an easy way to get the count of the quantity cell in order_items, displaying them down a table, and then calculating a total. I have everything fine and dandy minus getting the count of the quantity cell in order_items. Any ideas, I'd greatly appreciate it!
Wouldn't a simple select sum(quantity) work here ?
Is it ok to a mysql query inside a while loop using the ID of each row passed to fetch results from another table? OR is there a better way to do it?
$q = $__FROG_CONN__->query("SELECT cms_page.id, cms_page.title, cms_page.slug, cms_page_part.* FROM cms_page LEFT JOIN cms_page_part ON cms_page_part.page_id=cms_page.id WHERE cms_page.parent_id='8'");
$r = $q->fetchAll(PDO::FETCH_ASSOC);
echo '<ul id="project-list">';
foreach ($r as $row) {
echo '<li>';
echo '<img src="<img src="phpThumb/phpThumb.php?src=public/images/'.$row[0].'/th.jpg&w=162" alt="" />';
echo '<div class="p-text">';
echo '<h4>'.$row["location"].'<span>'.$row["project_date"].'</span></h4>';
echo '<p>'.$row["body"].'</p>';
echo '</div>';
echo '</li>';
}
echo '</ul>';
I am trying to pull the project_date, body and location fields from another table where the sql query matches. The title and slug are held in another table. There should only be a maximum of eight or so results but im getting alot more.
The suggestions using IN are fine, but if you are getting the ids from another query, it might be better to combine these two queries into one query using a join.
Instead of:
SELECT id FROM users WHERE age <30
SELECT id, x FROM userinfo WHERE userid IN ($id1, $id2, ..., $idn)
do:
SELECT users.id, userinfo.x
FROM users
LEFT JOIN userinfo ON userinfo.userid = users.id
WHERE age < 30
To reduce the overhead of preforming a query, you may want to look at getting all the data in a single query. In which case you may want to take a look at IN(), e.g.
SELECT * WHERE x IN (1, 2);
There is also BETWEEN()
SELECT * WHERE x BETWEEN 1 AND 2;
See the mysql docs for more information
I would try to build the query in a way where I only need to pass it once. Something like WHERE ID=1 OR ID=2 OR ... Passing multiple queries and returning multiple recordsets is expensive in terms of processing and network traffic.
This will be very inefficient, what you want is to join the tables on the ID
SELECT * FROM table1 LEFT JOIN table2 ON (table1.ID = table2.ID) WHERE condition
Mysql join documentation
This will return one set of rows with all the information you need, returned from both tables.
In a small application / small result set, this might be okay, but it results in a lot of (small) calls to the database.
If you can find an alternative way (perhaps see Yacoby's suggestion?) in which you can do one call to the database, this is probably better.
EDIT
If you are only interested in the IDs from one table, in order to get the correct results out of another table, perhaps a JOIN is what you are looking for?
SELECT t1.fieldA, t1.fieldB
FROM table1 t1
JOIN table2 t2 ON t1.ID = t2.ID
WHERE t2.someField = 'someValue'
Is it ok to a mysql query inside a while loop using the ID of each row passed to fetch results from another table? OR is there a better way to do it?
You should reformulate your query in SQL. Say, put the ids into a memory table and use it in a JOIN:
SELECT *
FROM idtable
JOIN mytable
ON mytable.id = idtable.id
This way, MySQL will make the loops for you but will make them in (usually) more efficient way.
SQL is a language designed to work with sets.
So if you have a set of ids and a table (which is a set of tuples), your first thought should be "how do I apply the set-based operations to these sets using SQL"?
Of course it is possible to run a bunch of simple queries in a loop but this way you just do extra work which SQL engine developers most probably have already done for you (and usually have done it in more efficient way).
You may want to read this article in my blog:
Double-thinking in SQL