Counting the number of results from a large database - php

I got a two database tables, one has 165 entries. For each of those, I got to browse the 1-million-entry table and see how many times is each of those 165 entries mentioned.
"odds_provider" has 165 entries, "bettingoffer" has a million entries.
$SQL = "SELECT
odds_provider.id AS id,
odds_provider.name AS name,
COUNT(bettingoffer.odds_providerFK) AS betcount
FROM odds_provider
INNER JOIN
bettingoffer
ON bettingoffer.odds_providerFK = odds_provider.id
WHERE
odds_provider.active = 'yes'
GROUP BY
odds_provider.id,
odds_provider.name
ORDER BY betcount DESC";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
echo $db_field['id'] , " " , $db_field['name'] , " " , $db_field['betcount'] , "</BR>";
}
It does what's intended but it takes forever. Is there a faster way?

This one should be faster, especially if there not many inactive ids.
SELECT id, name, betcount
FROM (
SELECT
odds_providerFK as id,
COUNT(*) as betcount
FROM bettingoffer
WHERE active = 'yes'
GROUP BY odds_providerFK
ORDER BY betcount DESC) as counts
USING (id);

You should be able to join the two tables using SQL. It would be best to not do a COUNT(*) though. You can get better performance by specifying the specific column you would want to count.
SELECT
op.id,
op.name,
COUNT(bo.odds_providerFK) AS bet_offering_count
FROM
odds_provider op
INNER JOIN
bettingoffer bo
ON bo.odds_providerFK = op.id
WHERE
op.active = 'yes'
GROUP BY
op.id,
op.name

You can do it in much better way using SQL Join queries. You don't have to search the 2nd table for each individual record in 1st table. You can establish a JOIN relationship between the tables.
It would be more helpful if you would have pasted the schema definition of both of your tables, but in general this is how JOIN queries works.
Kindly refer to these tutorials about how JOIN queries work.

Related

Distinct Values from MySQLi Query

I am trying to only show unique userIds (userIds are (0,1,2,3,4,5,6,7,8,9 etc...) for the query I am running. I tried using DISTINCT in my query, but it only shows me unique values of the rows that have 2 or more of the same userId.
Is there a way I can use php to only show the unique values. My weak points are arrays and it makes it more complicated because its using data from a MySQLi query.
Example right now I have with the query now (lets say its GROUP BY rentPaid DESC and the rent total is 800.00 for all users):
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
3--------400.00------April
1--------200.00------April
1--------100.00------April
Example desired output:
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
Can I do this with MYSQL because I tried DISTINCT and it wouldn't work, how about PHP?
Query:
SELECT
properties.*,
leases.*,
users.userId, users.primaryPhone,
CONCAT(users.userFirstName,' ',users.userLastName) AS user,
admins.adminName, payments.*
FROM
properties
LEFT JOIN leases ON properties.propertyId = leases.propertyId
LEFT JOIN assigned ON properties.propertyId = assigned.propertyId
LEFT JOIN admins ON assigned.adminId = admins.adminId
LEFT JOIN users ON properties.propertyId = users.propertyId
LEFT JOIN payments ON properties.propertyId = payments.propertyId
WHERE
payments.rentMonth = '$currentMonth' AND
payments.rentYear = '$currentYear'
Edit: Please excuse my formatting, this is my first post.
Edit: Added query....its long, but works lol. I only want unique userIds (no double or triple userIds etc...)
I suspect this is what you want:
SELECT userID, MAX(rentPaid) AS maxRentPaid, rentMonth
FROM yourTable
WHERE rentMonth = "April"
GROUP BY userID
ORDER BY maxRentPaid

Join a query into another query with column computation

I have three tables named issue_details, nature_payments, and rci_records. Now I have this query which joins this three tables.
SELECT issue_details.issue_date AS Date,
issue_details.check_no AS Check_No,
payees.payee_name AS Name_payee,
nature_payments.nature_payment AS Nature_of_Payment,
issue_details.issue_amount AS Checks_issued,
issue_details.nca_balance AS Nca_balance
FROM
issue_details
INNER JOIN
nature_payments ON
issue_details.nature_id = nature_payments.nature_id
INNER JOIN
payees ON
issue_details.payee_id = payees.payee_id
ORDER BY Date Asc, Check_no ASC
On my column in Nca_balance, this is a computed differences of every issuances of check. But you may not know what really the process of how I got the difference but to make it simple, let's say that I have another query
that dynamically get also the difference of this nca_balance column. Here is the query:
SELECT r.*,
(#tot := #tot - issue_amount) as bank_balance
FROM (SELECT #tot := SUM(nca_amount) as nca_total FROM nca
WHERE account_type = 'DBP-TRUST' AND
year(issue_date) = year('2015-01-11') AND
month(issue_date) = month('2015-01-11')
)
vars CROSS JOIN issue_details r
WHERE r.account_type = 'DBP-TRUST' AND
r.issue_date = '2015-01-11'
ORDER BY r.issue_date, r.check_no
I know it you may not get my point but I just want to replace the first query of the line
issue_details.nca_balance AS Nca_balance
with my own computation on my second query.
Please help me combine those two query into a single query. Thanks

Better way to do this subquery

Let's say I have this query:
<?
$qi = $db->prepare('SELECT one.id, one.Value, two.Name, three.nfid, temp.Name AS Alias
FROM one
INNER JOIN two ON one.fid = two.id
LEFT OUTER JOIN three ON two.fid = three.fid
LEFT OUTER JOIN (SELECT id,Name FROM two) AS temp ON three.nfid = temp.id
WHERE one.rid = ?
ORDER BY one.id ASC');
$qi->execute( array( $id ) );
?>
Connections between the tables are:
Table one contains a number of rows with the fields one.Value, one.rid and one.fid.
fid is a connection to table two which contains the two.Name of the items (one.fid = two.id).
But sometimes the item is an alias for another item, which is why table three exists. It contains the fields three.fid and three.newfid where three.newfid = two.id (but for another item with another two.Name)
The query is supposed to fetch all rows from one with a certain one.rid and get one.Value, two.Name and if there is an three.fid for this one.fid, get two.Name for three.newfid and call it Alias.
Is there a way to improve this query or solve the problem in another way? Perhaps reshape the layout of the database? It is currently quite slow. The example here have been simplified to make it more general.
Thank you.
The subquery in parentheses forces MYSQL to ignore its indexes, which makes it take a long time. Better to directly join two as temp. As long as you always put two.[field] and temp.[field], it will tell them apart just fine.
SELECT one.id, one.Value, two.Name, three.nfid, temp.Name AS Alias
FROM one
INNER JOIN two ON one.fid = two.id
LEFT OUTER JOIN three ON two.fid = three.fid
LEFT OUTER JOIN two AS temp ON three.nfid = temp.id
WHERE one.rid = ?
ORDER BY one.id ASC

Mysql Join Won't Select

I have been doing a lots of research online and from my understanding i think my query is ok
That is why i need your help to point me out what im doing wrong.
What My Query Should Do
My query should fetch our stock level from both warehouse
Problem Is
if the product is not in both warehouse the query dont give any result.
Ok so first i have two database of warehouse stock level. that look like that.
Databases
-warehouse1
-warehouse2
Table
-product
Columns
-id
-SKU
-qty
So my Query is
SELECT
warehouse1.product.id as 1_id,
warehouse2.product.id as 2_id ,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty,
warehouse2.product.qty as 2_qty
FROM `warehouse1`.`product`
LEFT JOIN `warehouse2`.`product`
ON
(`warehouse1`.`product`.`SKU` = `warehouse2`.`product`.`SKU`)
WHERE
warehouse1.product.SKU = '$sku'
OR
warehouse2.product.SKU = '$sku'
ORDER BY
(1_qty + 2_qty) DESC
if i make the where clause like this
WHERE warehouse1.product.SKU = '$sku'
it is then working but i can't get stock from both warehouse.
What should i do if i want to receive the stock level from both warehouse even if there is no product that im asking for in this database.
Thanks
Try a FULL OUTER JOIN. You're using a LEFT JOIN. That requires that the DB fetch all records that match your WHERE clause on the LEFT side of the join, which is warehouse1, and any potentially matching records from warehouse2 (the right side of the join). If a SKU exists only in warehouse2, you don't see it.
Switching to a FULL OUTER JOIN forces the DB to fetch all matching records from BOTH sides of the join, regardless of which side(s) the matching records exist on.
you can also do this with a union
(SELECT
warehouse1.product.id as 1_id,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty
FROM `warehouse1`.`product`
WHERE
warehouse1.product.SKU = '$sku' )
union
(SELECT
warehouse2.product.id as 2_id ,
warehouse2.product.SKU,
warehouse2.product.qty as 2_qty
FROM `warehouse2`.`product`
WHERE warehouse2.product.SKU = '$sku' )
Combine your OR's in () (... OR ...):
SELECT
warehouse1.product.id as 1_id,
warehouse2.product.id as 2_id ,
warehouse1.product.SKU,
warehouse1.product.qty as 1_qty,
warehouse2.product.qty as 2_qty
FROM `warehouse1`.`product`
LEFT JOIN `warehouse2`.`product`
ON
(`warehouse1`.`product`.`SKU` = `warehouse2`.`product`.`SKU`)
WHERE (warehouse1.product.SKU = '$sku'
OR
warehouse2.product.SKU = '$sku')
ORDER BY
(1_qty + 2_qty) DESC

Many to many relationship queries

I'm a bit confused about many to many relationship tables, and the code that goes with them.
I have table1:
id, username
And table2:
id, votes_up, votes_down
And a helper table (htable):
vu, vd, adsid
What I want to happen is, when an ad is voted up or down, this vote doesn't go to all adverts.
My attempt at selecting data:
mysql_query("SELECT *
FROM dbo.tab2
INNER JOIN dbo.htable
WHERE tab2.votes_up = htable.vu
AND htable.votes_down = htable.vd
INNER JOIN dbo.tab1
WHERE htable.adsID = table1.ID");
And my insert attempt:
mysql_query("INSERT INTO dbo.htable (vu, vd, adsid)
VALUES
(SELECT FROM dbo.tab2.votes_up, dbo.tab2.votes_down , dbo.tab1.id)");
My question: Are these two queries correct? If not, how can I fix them? and what is the update query ?
I do not really understand your question, but your SQL queries are wrong. They should probably be something like:
SELECT
*
FROM
dbo.tab2 as tab2
INNER JOIN dbo.htable as htable
ON tab2.votes_up = htable.vu
AND tab2.votes_down = htable.vd
INNER JOIN dbo.tab1 as tab1
ON htable.adsID = tab1.ID
and
INSERT INTO dbo.htable (vu, vd, adsID)
SELECT
votes_up, votes_down, ID
FROM
dbo.tab2

Categories