How to use join instead of select using mysql? - mysql

i want to find the sum of the items for the comp_id = 2
what i am trying to do?
i have two tables namely purchaseditems and item. both have comp_id in common. now i have to find the sum of items for the comp_id = 2.
below is how the tables look
As seen from above table i am expecting the sum to be 13.
so i have used the query below to get the sum of items for comp_id = 2.
SELECT sum(item.count) as sum FROM item, purchaseditems WHERE item.id = purchaseditems.item_id AND
purchaseditems.comp_id= 2;
How can i do the same using JOIN i am new to using mysql..still a beginner in this.
could someone help me fix this. thanks

You can use INNER JOIN to find the common rows between two tables matching a common column value. The below query should work for you:
SELECT sum(item.count) FROM item JOIN purchasedItems ON item.id = purchasedItems.item_id where purchasedItems.comp_id = 2
You may read about various types of joins

Related

SQL: Trouble returning distinct like values from a subquery and join

query:
select DOG_CD,ANIMAL_CD
from FKAGM
where FKAG = 12024
Displays 3 rows
DOG_CD - ANIMAL_CD are column names and below each column is 3 numerical values yielded from the above query & I have no clue how to draw a table on here to depict that. =(
There is a table called Dog_Animal that has a column called "Name" (Dog_Animal.Name) that I want to join with this above query. I want to join on ANIMAL_CD as FKAGM table and the DOG_ANIMAL table have the ANIMAL_CD column in common. I'd like to display "Name" right next to the ANIMAL_CD column. The issue is when I join the tables it displays like every instance of DOG_CD and ANIMAL_CD within the Dog_Animal table (Which is thousands) something similar to the below illustration. since the Dog_Animal table has thousands of DOG_CD and ANIMAL_CODE fields populated. I just want it to be limited to the three rows that are returned by the above query (Limit or distinct or something) and input the Dog_Animal.Name next to Animal_CD. I've been working on this for an hour and I know it must be so simple, but I can't seem to get it to work. I am not sure if a subquery is needed or exists, or case, or what. If you can figure this out I would be so thankful!
DOG_CD - ANIMAL_CD - Dog_Animal.Name with the same 3 rows of data just now a name included
select
f.DOG_CD,f.ANIMAL_CD,d.name
from FKAGM f
inner join dog_animal d
on d.animal_cd = f.animal_cd
where f.FKAG = 12024;
inner join would work for you. If you only need to limit it to 3 results, add limit 3 order by f.dog_cd at the end of your query.

MySQL Query Unique Results From Join

Struggling to find the right answer for this so hopefully someone can help. It maybe so simple that I've overlooked something obvious and making it more difficult than I should be.
I have two tables - titles [including titleIDs and titleNames], and groups [including groupIDs with title IDs they are associated with]. A titleID can have many groupIDs attached.
I'm trying to write a query that brings me back results of TitleIDs that match a criteria of groupIDs that have been selected.
So I've tried
SELECT * FROM titles INNER JOIN groups ON titles.titleID = groups.titleID WHERE
groups.groupID = 6 AND
groups.groupID = 24 AND
groups.groupID = 53
So I want to return results of only titles that are only associated with ALL these group IDS.
The numbers will actually be replaced by what someone selects from a few tickboxes, but have hardcoded them in for purposes of this example.
I tried experimenting with a subquery but I couldn't get it to work, also I believe Subs can slow things down and I'm already going to be dealing with a lot of data.
The plan is for someone to select one or more groupIDs from a list and then return only results of Titles that are associated with all the GroupsIDs selected.
Any pointers, clues, advice on this would be really welcome.
Thanks
You can do so by using in() for the group ids and matching the count of distinct groups foreach title,if 3 group ids provided so count for each title groups must be 3 so the title that has exactly these 3 groups will be returned
SELECT * FROM titles t
INNER JOIN groups g ON t.titleID = g.titleID
WHERE g.groupID IN(6,24,53)
GROUP BY t.titleID
HAVING COUNT(DISTINCT g.groupID) = 3

How do I sum [add] multiple columns from joined tables

I need to write a query that joins several tables and totals several columns in different tables & can't seem to figure out how to do it:
here are the tables:
The result I am trying to get is a result with the contract budgets for a particular budget name added: i.e. [this does not work but gives an idea]
select c.contract_budget_f1, c.contract_budget_f2, cb.budget_type_id, c.id, sum(cb.budget_f1) as bf1, sum(cb.budget_f2) as bf2
from `flow_contract` c
left join `flow_contract_budget` cb on cb.contract_id = c.id
where c.program_id = '69'
group by cb.budget_type_id
with the whole result set looking like:
[budget_type_id]
[contract_budget_f1]
[contract_budget_f2]
[bf1]
[bf2]
where it will return 3 rows with the budgets for each budget type added
How can I do this, is it even possible?
Here are links to the tables - sorry, didn't realize you couldn't click on them...
http://media.bigblockstudios.ca/stack/program-name.gif
http://media.bigblockstudios.ca/stack/contract-budget.gif
http://media.bigblockstudios.ca/stack/contracts.gif
UPDATE
I got it working like this:
select c.id, c.program_id, c.contract_budget_f1, c.contract_budget_f2, cb.budget_f1, cb.budget_f2, cb.budget_type_id, c.id,
sum(cb.budget_f1) as bf1, sum(cb.budget_f2) as bf2
from `flow_contract` c
left join `flow_contract_budget` cb on cb.contract_id = c.id
where c.program_id = '".$formfields['program_id']."'
group by cb.budget_type_id
order by cb.budget_type_id
I think what you want is:
group by cb.budget_type_id, cb.contract_id
Or the other way around. Could you make an sql fiddle?
Short Answer: subquery
Try this:
Start with a subquery.
Write a query that produces the column values that you want to sum. This is now the subquery.
Write an outter query that sums the desired columns in the inner query.
After you get it working, review it to see if you can optimize out the subquery and just have one query.

Restricting sub-query to 2 arguments in same row

It's been hours that I've been searching for a solution (books, internet, etc) and can't find anything. Here's my problem:
I got a table of items being tagged by 2 criteria: let's name them crit1 and crit2. For each of the items I can have for crit1 and crit2 the following int example values (criteria1,criteria2): (1,5) (5,2) (4,7) (8,6), etc.
In another table I store users that are subscribed to some of these items filtered by the above criteria. Let's say that user_id 1 is subscribed to the following item type (criteria1, criteria2): (1,5) (2,7). When I make my query to fetch the items that user 1 is subscribed to, I get the items tagged with (1,5) (2,7) but also (1,7) or (2,5). The SQL Select query is making cross-comparisons between each row.
Generally, I would like to know how to make a query that is filtered from more than 1 field in the same row (no cross-row allowed).
I tried to use JOINS to sort the problem but I can't link criteria1 and criteria2 in the same JOIN. I have to use 2 JOINS and that makes them independent (and the cross-comparison between criteria1 and criteria2 will happen).
Use AND operator in ON clause for JOIN:
SELECT i.* FROM subscriptions s
JOIN items i
ON i.crit1 = s.crit1 AND i.crit2 = s.crit2
WHERE s.user_id = 1
without seeing the rest of the structure specifically, I'll give it a shot like...
select
i.itemid,
i.itemDescription,
s.subscriberName
from
items i
join Subscribers s
on i.category1 = s.category1
AND i.category2 = s.category2
If this isn't it, you might need to dump some sample data from each respective table of what you are trying to actually get.
Try this:
multiply crit 1 by 1000 (or some other number-depending or size of numbers) and add to it Crit2
Use that formula in your where or join

Mysql Query - Joins causing confusion for me in this query

I have a query that returns results related to items that match a specific category...
There are 3 mysql tables that results to this, items, categories and item_categories.
These i assume are self explanatory, but the latter, is a linking table that links any specific item to any specific category, using a match of id's.
The items table contains one row, with an id value of 1.
The categories table is filled with 15 rows, with id values of 1-15.
the item_categories table contains one row, the item_id value is 1 and the category_id value is 5.
This is the mysql query in its php form:
$catResultQuery = "
SELECT i.id, name, price
FROM items i
INNER JOIN item_categories
ON i.id = item_id
INNER JOIN categories c
ON category_id = c.id
WHERE MATCH (c.id)
AGAINST ('{$_SESSION['input']}' IN BOOLEAN MODE)
ORDER BY name
";
The session variable has a value of 5, but for some reason, this query displays a 0 result set.
Even when i run the query in php myadmin, it returns 0 rows.
And i am confused, because in my head, the logic behind all of this seems fairly simple, but for some reason i get 0? Does anyone have any idea where i have gone wrong with this?
Any advice and input would be greatly appreciated, thank you!!
Ok, I see now that you're building the SQL dynamically. If that's the case, then this should work:
SELECT i.id, name, price
FROM items i
INNER JOIN item_categories
ON i.id = item_id
INNER JOIN categories c
ON category_id = c.id
WHERE c.id
IN ('{$_SESSION['input']}')
ORDER BY name
Just make sure '{$_SESSION['input']}' is comma delimited and be aware that this carries the risk of SQL injection because you're constructing the SQL on the fly.