MySql SELECT get 1 record from multiple record - php

I have a table which looks something like :
id name qty price rev
1 book1 2 $10 0
2 book2 1 $5 0
3 book1 3 $15 1
4 book3 2 $10 0
5 book4 3 $15 0
6 book2 3 $15 1
7 book2 4 $20 2
and the data that will be displayed on the web is,
no name qty price rev
1 book1 3 $15 1
2 book2 4 $20 2
3 book3 2 $10 0
4 book4 3 $15 0
This is the query that I use
<?php
$sql = mysql_query("SELECT SUM(qty*price) FROM data_ph_user ORDER BY id");
while($res = mysql_fetch_array($sql)){
?>
<!-- display result -->
<?php
$resf1 = $res['SUM(qty*price)']; if($resf1 == 0){ echo '0'; }else{ echo $resf1; }
?>
<!-- end display -->
<?php } ?>
so, now how to get the data?
I've done various kinds of queries by using 'WHERE' but do not get results

I got your point.. so you just want to select the line where qty is maximum per book name.. right??
try the below query
select
name, qty, price, rev
from
MyTestingTable
where
qty = (select max(qty) from MyTestingTable i where i.Name = MyTestingTable.Name)
order by MyTestingTable.name
you can have a look on given SQL fiddle as well.. it will give you the desired result..
http://sqlfiddle.com/#!2/9162c4/8

The reason is that SUM is an aggregate function. Such functions normally return one row: in this case, you would sum over the entire table unless you group by something.
If I understand your question correctly, you wish to list the highest revision of all elements?
SELECT *, MAX(rev) FROM data_ph_user GROUP BY `name`
Then it's only a matter of typesetting it correctly.

Related

Update multiple rows with one value and divide it to the different row in single SQL query

Basically I have two tables itemTable and stockTable, every time I add a stock, I will get the foreign key for itemId and add it in stockTable with quantity.
I want to update the stockquantity in stockTable every time the customer will buy a product.
PROBLEM:
For example the customer will buy 7 shirt:
SO FIRST WILL UPDATE ON THE STOCKID (3) QUANTITY OF 4
SECOND WILL UPDATE THE STOCKID (6) QUANTITY OF 3
SO THE TOTAL STOCKS OF SHIRT IS 3 AFTER UPDATING THE QUANTITY
THE STOCKID (3) WILL BECOME 0
THE STOCKID (6) WILL BECOME 3
HOW DO I QUERY THAT IN SQL.
THANK YOU!
TOTAL STOCKS: (Base on the same itemName)
SHOES - 5
SHIRT - 10
BALL - 15
stockTable
stockId itemId stockQuantity stockOut
1 35 5
3 89 4
6 11 6
14 87 15
itemTable
itemId itemName itemSellPrice supplierName
35 shoes 50 Jason
89 shirt 40 Jacob
11 shirt 65 Max
87 ball 150 Sam
First of all you need to identify the itemId(s) that must be updated, they are in the result of:
SELECT itemId FROM itemTable WHERE itemName = 'shirt'
Having said that the update query will look like this:
UPDATE stockTable SET ... WHERE itemId IN (SELECT itemId FROM itemTable WHERE itemName = 'shirt')
Obviously now we need to update the quantities, this must be done progressively until the order is complete starting from the lowerst itemId (for istance):
SELECT IF(stockQuantity>7,#remaining_qty:=stockQuantity-7,#remaining_qty:=#remaining_qty-stockQuantity) AS `remaining_qty` FROM stockTable WHERE itemId IN (SELECT MIN(itemId) FROM itemTable WHERE itemName = 'shirt';
UPDATE stockTable SET stockQuantity=IF(stockQuantity>7,stockQuantity-7,0) WHERE itemId IN (SELECT MIN(itemId) FROM itemTable WHERE itemName = 'shirt');
After that you can check the variable #remaining_qty, and reapeat the stuff until #remaining_qty>0.

Group by with 3 columns

I have 3 columns to get data.
1- amount, 2- transaction_id and order_id
Made group by (transaction_id), sum(amount) and get all order_id.
id order_id transaction_id amount
1 1 3333 698.00
1 2 3333 758.00
1 3 3333 560.00
1 4 3333 360.00
1 5 5555 225.00
1 6 5555 102.00
1 7 2222 36.00
See image
TABLE
SELECT sum(amount) as sum, transaction_id, order_id FROM table WHERE ID='1' GROUP BY transaction_id
Got back:
The sum is OK.
The transaction id is OK.
The order id got back just the first of each transaction id.
I what to see order id like this transaction id 3333 - order id 1,2,3,4
Tried explode() but did not work
Help needed.
Assuming the db is mysql (please tag your db in the question), use group_concat for this like:
SELECT sum(amouNt) as sum, transaction_id, group_concat(order_id) orders FROM table WHERE ID='1' GROUP BY transaction_id
This will return orders column with comma separated values like 1,2,3,4

SQL Get max ID grouped by a second ID

I am working on a php/mysql best before date checking system and upon creating a new check I need the system to find a best before date for a certain product by looking for it most recent closed check
I am working with a few tables to get this done:
bbcheckProducts
ID checkID productID checked bestBefore
1 1 1 1 2015-05-06
2 2 1 1 2016-07-22
3 3 1 1 2016-09-16
bbChecks
checkID userID closed
1 1 1
2 2 1
3 1 1
So when I run this query on the tables in the image above:
SELECT ID,
MAX(checkID) AS maxCheck,
bestBefore
FROM bbcheckProducts
WHERE checkID IN
(
SELECT checkID
FROM bbChecks
WHERE userID = 1
AND closed = 1
)
AND checked = 1
GROUP BY productID
ORDER BY bestbefore ASC
it returns something like this:
ID = 1
maxCheck = 3
bestBefore = 2015-05-06
so it does take the max checkID but the other values remain equal to the first occurence of productID. I want it to take the values that go together with that max ID so the result would look like this:
ID=3
maxCheck = 3
bestBefore = 2016-09-16
so how do I get my query to work like that?
NOTE: there are multiple products so product one may be in check 1 and 3 while product 2 is only in 1 so it has to take the data of product 2 from check 1 and the data of product 1 from check 3
You need to use max function on second table like this query
select * from table_name where some_colomn = 'some_value' and some_colomn
in (select max(some_colomn) from table_name2 where some_col = 'some_value' group by some_colomn)
You could join your tables to get a reduced set of all record with an check_ID existing in your bbChecks-table.
Then you can run your max(CheckID)-selection on the reduced set.
In your case this would like like that:
SELECT ID, max(checkID), bestBefore
FROM bbcheckProducts p
INNER JOIN bbChecks c ON (p.checkID = c.checkID)
WHERE UserID = 1
AND closed = 1
AND checked = 1
This returns you first of alle the records with the checkIDs 1 and 3. And then you select the max(checkID), so it returns you the checkID 3.

MySQL Joins and ORDER BY in PHP / MYSQL

I have a database that looks like this with two tables
Items
id | Title
-----------------------------
1 Bus
2 Plane
3 Jet
4 Shoes
5 Chair
Sorting
id | CatID | ItemID | SortOrder
-------------------------------------------------------------------------------
1 3 3 3
2 3 2 1
3 3 4 2
4 3 1 0
5 4 5 4
I can't figure out how to list the Titles of the ITEMS table based on the "SortOrder" Column of the SORTING table.
Here is what I tried so far:
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder
I'm not sure what I'm doing wrong
EDIT
It looks like the MySQL query is correct, the problem is happening because when I output the $row['id'] of the Items Table it is incorrect. I have an Ajax PHP update that is updating the database based on the id of an li tag.
Any ideas why the $row['id'] is outputting incorrectly? I think it has something to do with the Items.id = Sorting.ItemID
This works as expected - SQLFiddle DEMO:
SELECT i.*, s.SortOrder
FROM items i, sorting s
WHERE i.id = s.ItemID
AND s.CatID = 3
ORDER BY s.SortOrder
Try
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder ASC
add DESC or ASC in ORDER BY clause.
if you use ASC then sorted result will be 0 1 2 3 4 for SortOrder.
sample php code to get title
<?php
$query = mysqli_query(above_query)or die(mysqli_error());
while($result = mysqli_fetch_assoc($query))
{
echo $result['title']. '<br/>';
}

mysql IF EXISTS

I have this table
UMS
id_attribute value order
1 MB 1
1 Gb 2
1 TB 3
...
and this table
ATTRIBUTE_VALUE
id id_attribute value name ums
1 1 50 hdd GB
2 1 100 hdd TB
3 2 15.00 price NULL
and i want to select from ATTRIBUTE_VALUE where id_attribute=1 and if exist (UMS.value=ATTRIBUTE_VALUE.ums) then order by UMS.order end if group by ATTRIBUTE_VALUE.value
example for output :
50 GB
100 Tb
and must to appear
15.00 !!! here is the problem because in my UMS table i don't have UMS for price
but it doesn't appear
Update after you clarified your question - Try something like this:
SELECT T1.*
FROM ATTRIBUTE_VALUE T1
LEFT JOIN UMS T2
ON T1.id_attribute = T2.id_attribute AND T1.ums = T2.value
ORDER BY T2.order, T1.value
But note that this will fail if T1.value is greater than 1000. It might be better to convert all units to the same type before ordering them.
Result of query:
id id_attribute value name ums
3 2 15.00 price
1 1 50 hdd GB
2 1 100 hdd TB
You can make a conditional order by in mysql, like this, for example:
user
id name
select *
from user
order by (case when id <5 then id else name end)
However, you've got two tables, you need yo join them, I'm still not sure if you can get what you need this way.
Also, you can't order with DESC on one branch and ASC on another.
Finlay I have get my own answer:
this is the code:
$nr_ordine=0;
$virgula="";
$ordine="valoare";
$ordine2="FIELD(unitate_masura,";
$sql_ums=mysql_query("select * from atribute_masura where id_atribut='".$exe_atribut['id']."' order by ordine asc");
while($exe_ums=mysql_fetch_array($sql_ums))
{
$nr_ordine++;
if($nr_ordine>1)
{
$virgula=",";
};
$ordine2.=$virgula."'".$exe_ums['valoare']."'";
};
$ordine2.=")";
if($ordine2!="FIELD(unitate_masura,)")
{
$ordine=$ordine2;
};
$s_q0=mysql_query("select * from atribute_cautare where id_atribut='".$exe_atribut['id']."' group by valoare order by $ordine asc") or die (mysql_error());
while($s_q=mysql_fetch_array($s_q0))
{
...
};
The names not correspond with my question but this is the idea order by FIELD (ums,'kb','mb','gb','tb')

Categories