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')
Related
We require to get row if product_id is in sequence.
Table (product)
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
6 Nuts
8 Britania
9 Pepsi
Require Output
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
6 Nuts
product_id - 8 and 9 not getting because it is not in sequence.
My Try
select distinct t1.*, t1.product_id, (select GROUP_CONCAT(t2.product_id) from product as t2) as p_id
from product t1
having FIND_IN_SET(t1.product_id+1, p_id)
Output
product_id name
1 Parle
2 Coconut
3 Pizza
4 Colgate
5 Ice Cream
In this try i am not getting product_id - 6 row.
Note : I want MySql query not in PHP.
Thank You !
One way i can think of is to user user defined variable to get the rank of row and then calculate the difference of product id and rank and select only those rows where difference = 0
select *
from(
select f.*,#row:= #row + 1 rank,
product_id - #row as diff
from product f,
(select #row:= 0) t
order by product_id
) t1
where diff = 0
Demo
Or if you want to pick the least sequence no. automatically you can write it as
select *
from(
select f.*,#row:= #row + 1 rank,
product_id - #row as diff
from product f,
(select #row:= (select min(product_id) from product_sale_flag) a) t
order by product_id
) t1
where diff = -1
Demo
Explanation
First query assign's minimum value of product_id to variable #row,then it assigns a rank to each row ordered by product_id in ascending order, once rank is assigned for every row then it calculates the difference between the original value of product_id and lastly using the resultant difference it checks where difference is 0 get those rows because they follow the sequence. Hope this makes sense
s.no Name type of vehicle allotted
1 ram bus
2 krish car
3 raj bus
4 albert car
5 johnson bike
6 raghu car
consider this is a table now i want to retrieve the type of vehicle which is there more number of times in the table and count of it. is there any particular method(query).
You have to use COUNT and GROUP BY.
Count will give you the number of rows grouped by type field.
SELECT COUNT(id) as count, type FROM table_name GROUP BY type
The output should be like this:
count | type
2 | bus
3 | car
1 | Bike
If you need just the highest one, append to the query:
ORDER BY count DESC LIMIT 1
I think you have to count and select the top 1 row.
Query
SELECT t.* FROM(
SELECT `type`, COUNT(`type`) `count`
FROM `your_table_name`
GROUP BY `type`
)t
ORDER BY `count` DESC LIMIT 1;
I need a small hint... I've got 2 Tables.
Table 1 gets data from an external api.
Table 2 is static.
Table 1: data
id name status ratio import_id
1 Test online 3 1
2 Tee online 2 1
3 Test online 1 2
4 Tee online 0.01 2
5 Test offline 4 3
6 Teee online 3 3
7 Teet online 1 3
Table 2: names
id name tag active
1 Test t1 1
2 Tee t2 1
3 Teee t3 0
4 Teet t4 1
I want to have the ID from the table names (to write into another table and execute a cronjob)
Explanation Table 1:
id - AI
name - just the name
status - if the entry is active
ratio - the main select
import_id - every 10 minutes I do import from json (~40 entries)
what i've got:
$result = mysql_query("
SELECT
import_id
FROM
data
ORDER BY id DESC LIMIT 1");
while($raw = mysql_fetch_object($result))
{
$the_id = $raw->import_id;
echo $the_id;
}
Now I've got the ID and try to get the latest entry (import_id) with the highest ratio:
$c_result = mysql_query("
SELECT
name, active, ratio, import_id
FROM
data
WHERE
active = '1' AND import_id = '$the_id'
ORDER BY
ratio DESC LIMIT 1");
while($chosen = mysql_fetch_object($c_result))
{
$the_c = $chosen->name;
echo $the_c;
}
That works flawless.
But it is possible that one of the 40 entries provided by api is not in my table "names" or it is not marked as "active".
But I only want the names.id of
the name with the highest ratio
which is in my table "names"
which is marked as active in "names"
and the data.status is online
which is from the latest import (highest import_id)
and write it to another table.
I thought about a LEFT JOIN but if the names.name is not in the table "names" i just get an empty result.
Have you got a hint in the right direction?
SELECT d.name, active, ratio, import_id
FROM data d
JOIN names n ON d.name = n.name
WHERE import_id = (SELECT import_id
FROM data
ORDER BY id DESC
LIMIT 1)
AND d.status = 'online'
AND n.active = 1
ORDER BY ratio DESC
LIMIT 1
DEMO
This is kind of hard to explain so I'll break it down...Here's the objective
Suppose you have a table
ID | Weight
1 2
2 4
3 8
4 66
5 11
6 44
7 33
And suppose I have a set of interested IDs, say (3,4)
My objective is to get two other rows (one for each of the two interested IDs) such that the row that matches with the interested ID has a weight that is one level less than the weight of the interested ID
so in this case
for id 3, we want to return row with ID 2 and weight 4 since row id 2 is the first row of which the weight (4) is less than the weight of row id 3 (8)
for id 4, we want to return row with id 6 and weight 44 since row id 6 is the first row of which the weight (44) is less than the weight of row id 4 (66)
How would you accomplish this with mysql in one single query whereby we use the IN() notation for the interested IDs.....
I'd like to propose the following (used ourtable as table name obviously)
SELECT id,weight FROM ourtable WHERE weight IN (SELECT MAX(t.weight) FROM ourtable t,ourtable t2 WHERE t.weight < t2.weight && t2.id IN (3,4) GROUP BY t2.id);
it gives the following result
+----+--------+
| id | weight |
+----+--------+
| 2 | 4 |
| 6 | 44 |
+----+--------+
as requested.
You could solving this selecting the first row of a selection of the rows ordered by weight desc which weight is lower than the given weight, in this case for mysql something like:
select * from t where weight < (select weight from t where id = :id) order by weight desc limit 1
in a in statement following the idea above, you could have something like:
select * from (select id, (select weight from t where weight < (select weight from t where id = tp.id) order by weight desc limit 1) from t tp) a where id in (3,4)
Another solution w/o subquery:
select w1.id,w1.weight,
left(group_concat(w2.id order by w2.id desc ),LOCATE(',', group_concat(w2.id order by w2.id desc ))-1) as w2_id,
left(group_concat(w2.weight order by w2.weight desc ),LOCATE(',', group_concat(w2.weight order by w2.weight desc ))-1) as w2_weight
from weight as w1, weight as w2
where w2.weight < w1.weight
and w1.id in (3,4)
group by w1.id
I have written a query which returns all records with some many-to-many joins correctly for the entire set or an individual article using WHERE a.id = ?
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id
LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id
LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id
LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
BUT!
I've hit a brick wall trying to work out how to limit the articles to a specific number of IDs, for working with pagination.
I'm ideally trying to use as simple and clear SQL statements as possible because I'm using the codeigniter framework with their active record class.
http://codeigniter.com/user_guide/database/active_record.html
Would really appreciate some help as I don't want to revert to using multiple queries for this as I've tried to reduce it down to a single query for database efficiency.
Have search around and tried some alternatives but nothing seems to work. Many thanks!
For example the results I return are like this
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
2 test 2 2 1 1
2 test 2 1 2 1
2 test 2 1 1 2
2 test 2 5 1 1
2 test 2 8 1 1
2 test 2 1 4 1
2 test 2 1 4 2
I need the results like this so that I can create sub-arrays in the php like this:
$articles = $query->result_array();
$output = array();
foreach ($articles as $article) {
// set up article details
$article_id = $article['id'];
// add article details
$output[$article_id]['article_id'] = $article_id;
$output[$article_id]['date_added'] = $article['date_added'];
$output[$article_id]['title'] = $article['title'];
$output[$article_id]['content'] = $article['content'];
// set up people details and add people array with details if exists
if (isset($article['person_id'])) {
$person_id = $article['person_id'];
$output[$article_id]['people'][$person_id]['person_id'] = $person_id;
$output[$article_id]['people'][$person_id]['lastname'] = $article['lastname'];
$output[$article_id]['people'][$person_id]['firstname'] = $article['firstname'];
}
// set up organizations details and add organizations array with details if exists
if (isset($article['organization_id'])) {
$organization_id = $article['organization_id'];
$output[$article_id]['organizations'][$organization_id]['organization_id'] = $organization_id;
$output[$article_id]['organizations'][$organization_id]['organization_name'] = $article['organization_name'];
}
// set up categories details and add categories array with details if exists
if (isset($article['category_id'])) {
$category_id = $article['category_id'];
$output[$article_id]['categories'][$category_id]['category_id'] = $category_id;
$output[$article_id]['categories'][$category_id]['category_name'] = $article['category_name'];
}
}
But if I just use LIMIT (with offset etc) 1
the results I get are
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
instead of
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
which is my desired result.
OK, so finally I worked out how it is possible.
Thought i'd include it here in case anyone else has the same problem.
Changing this line
FROM articles AS a
to this
FROM (SELECT * FROM articles LIMIT 5,3) AS a
does what I wanted.
So, why don't you use OFFSET 0,10 and LIMIT *number_of_results* in the SQL Query? (if I understood the question)
Specific number of IDs... WHERE ID IN (2,4,6,8)... ?
Are you using codeigniter's pagination?
http://codeigniter.com/user_guide/libraries/pagination.html
You can easily limit the number of records that are being returned using the MySQL LIMIT clause. This can be achieved like the following with your sample query.
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
LIMIT 10
Where 10 is the number of records you wish to display. The MySQL LIMIT clause allows you to specify a limit of the number of records and an initial offset. Like so:
LIMIT <offset>,<limit>
In your case <offset> would be the current page * the number of records on a page. <limit> would be the number of records you would like to display per page.