I would like to search my database via SQL command for the last value and for a given ID.
The ID works so well:
SELECT * FROM 'tem2' WHERE macid = '*'.
Unfortunately, if I add LAST ( SELECT LAST * FROM...) it does not work anymore.
SQL tables represent unordered sets. There is no "last" value unless a column specifies the ordering. Let me assume you have one.
Use order by and limit:
SELECT *
FROM tem2
WHERE macid = '*'
ORDER BY <ordering col>
LIMIT 1;
The ordering column would be a creation date or auto-incremented id.
Related
I have one such sql:
select name from A where id in (23,24,22,23)
When I run it in Navicat, the result only have one result of 23.
My question is, how to keep the number and order of the query results remains the same as (23,24,22,23).
If you want to maintain the order of the result then use order by clause like
select name from A
where id in (23,24,22)
order by id;
Again, assuming that id is a primary key column in your table A then there will be only one row with id = 23. How do you expect the same row to get repeated automatically unless you make it explicit by using a UNION ALL
If you really really want to fetch the records like this, you can use field function to get 23,24,22 and order by this sort:
select name from A where id in (23,24,22) order by field(id, '23,24,22')
then use union all get another 23:
(select name from A where id in (23,24,22) order by field(id, '23,24,22'))
union all
select name from A where id = 23
I have a column that lists all the units ids from a company which are allowed to see a specific document.
Like this:
And those ids are selected here ('Selecionar todas' mean 'Select All'):
The problem is when I add a new Unit, it come unselected and it will be a headache to have to enter in all of the documents that are supposed to show to all units and change it to be selected.
Is there a way to insert the new Unit's id into the 'idsunidades' column where there are all the other units selected ?
Sorry for the bad English.
To implement a select all option you should use a flag column all_selected(true or false) or you can do it like this:
To select the rows where All units are selected should have the longest value of idsunidades, you can select them like this
SELECT #maxLength:=LENGTH(idsunidades)
ORDER BY LENGTH(idsunidades )
DESC LIMIT 1
You can use CONCAT() to append the new id to the old column data
To add the unit 99 to the column idsunidades to all the rows with all units you can do this
UPDATE table set idsunidades=CONCAT(idsunidades, ',99')
WHERE LENGTH(idsunidades) = (SELECT LENGTH(idsunidades)
ORDER BY LENGTH(idsunidades )
DESC LIMIT 1)
I have a table in which there is column name as mappedcloumnname and fieldname and my fieldcolumn contains address1, address2, city, state, customerid, country and mappedcolumn contanins c1-c20. I wrote a query to sort my data based on mappedcolumn name but the order what am getting is wrong one
SELECT * FROM customermetadata
WHERE OrgID = in_orgid
ORDER BY MappedColumnName;
You can give it a try:
SELECT
*
FROM
customermetadata
WHERE
OrgID = in_orgid
ORDER BY CAST(SUBSTRING(MappedColumnName FROM 2) AS UNSIGNED);
Note:
Here I've extracted the number from the MappedColumnName and sort the records based the extracted numbers.
I've created a demo where the table contains only two columns (id and col).
col column contains value like c1,c2,....
See demo if you order by col only.
See demo if you order by extracting number from col.
If your column MappedColumnName contains value from c1-c20, then it will be treated as String(VarChar) in SQL and data will not be sorted properly.
You should try in this way,
select * from customermetadata
where OrgID=in_orgid
Order By CAST(SUBSTR(MappedColumnName FROM 2 FOR LENGTH(MappedColumnName)) AS UNSIGNED); ;
NOTE: A longer number is also a bigger number for numbers of the same length, you can make a textual comparison, because '0' < '1' .... < '9' and it will short Alpha-numeric order.
I've a search log table, I keep search logs. Table structure is like searchstring, date, number of results of each search string as results and some other info. I have the following SQL that I get records I need. A keyword could be searched several times so latest date is important. I use following SQL to get records I need. It's working fine.
SELECT id, searchstring, max(logdate) as logdate
FROM log_search
WHERE locale = 'en' AND results > 0
GROUP BY searchstring
ORDER BY logdate DESC
My problem is there are millions of records and I need to clean it up. I just want to keep records that matches sql above.
I tried to use NOT IN over id field but since sorting by logdate is important didn't let me.
DELETE FROM log_search WHERE id NOT IN (...MYQUERY...) but it gives Operand should contain 1 column(s) error
Another important field is locale . While deleting records for en I need to keep other locales even though they don't match my SQL above.
Is there a way to delete records and keep the ones I need.
EDIT
Table structure
Id - Auto increment
searchstring
results - containt number of results for that searchstring
logdate - date and time that search is made
results and logdate both are important to get latest query that return result.
SOLUTION / WORKAROUND
#Sunny's answer technically works, but for big tables like some millions of records, it's performance is awful. Insted, I did a workaround by creating another table and inserting records I need into there. Here is my SQL
INSERT INTO log_search_simple
SELECT id, searchstring, max(logdate) as logdate, locale
FROM log_search
WHERE locale = 'en' AND results > 0
GROUP BY searchstring
ORDER BY logdate DESC
Your try is right you just need to select one column of id instead of multiple columns.
Try that.
DELETE FROM log_search FROM log_search WHERE id Not in (SELECT id FROM log_search WHERE locale = 'en' AND results > 0 GROUP BY searchstring )
You may try this...
Delete from log_search where NOT EXISTS (SELECT id, searchstring, max(logdate) as logdate
FROM log_search
WHERE locale = 'en' AND results > 0
GROUP BY searchstring
ORDER BY logdate DESC)
try this:
DELETE FROM log_search where id NOT IN(
SELECT id FROM (
SELECT id, searchstring, max(logdate) as logdate
FROM log_search
WHERE locale = 'en' AND results > 0
GROUP BY searchstring
ORDER BY logdate DESC
) AS a);
Operand should contain 1 column(s)
It looks for 1 column to match data for a column and for here it is getting three columns in result set by SELECT statement. So the quick solution is to slice a column from the result set and match the column. it will do the trick :)
Is there any way to do something like :
SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1;
?
No, you can't. Column order doesn't really matter in MySQL. See the below question for more details.
mysql - selecting values from a table given column number
If your table has a column named COLUMN_NUMBER and you want to retrieve rows from the table where that column contains a value of '1', that query should do the trick.
I suspect that what you are trying to do is reference an expression in the select list with an alias. And that is not supported. An expression in the WHERE clause that references a column must reference the column by name.
We can play some tricks with inline views, to give an alias to an expression, but this is not efficient in terms of WHERE predicates, because of the way MySQL materializes a derived table. And, in that case, its a name given to the column in the inline view that has to be referenced in the outer query.
How I did it:
I'm trying to take (last 3 values of) column number 4 in sometable.
set #mydb=(SELECT DATABASE());
set #mycol=(select COLUMN_NAME from information_schema.columns where
table_schema=#mydb and table_name='sometable' and ordinal_position = 4);
SELECT Date,#mycol FROM sometable ORDER BY Date DESC LIMIT 3;
Of course, if Database name is known, first line could by whiped and #mydb replaced by real database name.
You can do this trick
Example:
$query="select * from employee";
$result=mysql_query($query);
$meta=mysql_fetch_field($result,0) // 0 is first field in table , 1 is second one ,,, etc
$theNameofFirstField=$meta->name; // this well return first field name in table
// now you can use it in other query
$seconQuery="select $theNameofFirstField from employee";