How to fetch primarykey from table based on a condition? - mysql

+----+------+
| id | name |
+----+------+
| 1 | Foo1 |
| 2 | Foo2 |
| 3 | Foo3 |
+----+------+
"id" is the primarykey here.
My query:
SELECT id FROM tablename where name='Foo1';
MYSQL showing only column name but no values.

try
select id from `table` where name = 'Foo1';
TABLE is a reserved word, to use it as a table name enclose it in backticks. Your original query is throwing an error, thus the empty result.

It is better to use LIKE clause while comparing strings i.e:
SELECT id FROM `table` WHERE TRIM(name) LIKE 'Foo1';
or
SELECT id FROM `table` WHERE name LIKE 'Foo1';

Assuming cases match, there must be some leading and/or trailing whitespaces in data that need to be trimmed in the query:
SELECT id FROM `table` WHERE TRIM(name)='Foo1';
Otherwise, use UPPER in both sides of the = to make it work.

Related

Remove SQL duplicates

I'm totally new in SQL. I never used it and just need a simple answer because I don't have time to learn SQL right now :(. I need to remove duplicated records from my local DB. Case looks like this:
| id | type | ... |
-------------------
| 1 | test | ... |
| 1 | test2 | ... |
| 1 | test | ... |
| 1 | test | ... |
I want to remove all duplicated record which has the same id and type but leave only on record. Like this:
| id | type | ... |
-------------------
| 1 | test | ... |
| 1 | test2 | ... |
Using delete by Id is impossible. I have 50k records and I want to remove all duplicated records. When ID and Type are the same.
Please try this
First Way
SELECT id, type
FROM table_name
Group by id, type
Second Way
SELECT DISTINCT id, type
FROM table_name;
A TSQL sample code that might help:
WITH tbl_alias AS
(
SELECT id, type,
RN = ROW_NUMBER()OVER(PARTITION BY id, type ORDER BY id)
FROM tbl
)
DELETE FROM tbl_alias WHERE RN > 1
Also you can try How to delete duplicates on a MySQL table?
.
SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
In your table
SELECT DISTINCT id, type, ...
FROM table_name;
you just need to use the keyword distinct when selecting mate.. try like this
SELECT DISTINCT id, type, blah blah blah FROM your_table; // this should take care of em
You should replace your table grouping by id and type, and using an aggregate function on the other fields.
You should add to your question the definition of your table and specify the rule to use to get the other fields. Anyway, this is a simple solution:
-- Create a temp copy of original table with distinct values
CREATE TEMPORARY TABLE copy_table1
SELECT id, type, MIN(field3) AS field3, ...
FROM table1
GROUP BY id, type;
-- Empty original table
DELETE FROM table1;
-- Insert distinct data into original table
INSERT INTO table1 (id, type, field3, ...)
SELECT id, type, field3, ...
FROM copy_table1;

Get path with specific number of values

I have a SQL table with the following values:
+---------+----------+
| post_id | path |
+---------+----------+
| 1 | 1/ |
| 2 | 1/2/ |
| 3 | 1/2/3/ |
| 4 | 1/2/3/4/ |
| 5 | 1/2/5/ |
+---------+----------+
How can I create a query that would get the path with the exact number of values separated by slashes?
For example, if I wanted all post_ids where the path is exactly 1/%/%/ (where each % represents a single number), meaning return anything of the form 1/2/3/, 1/2/5/, but not 1/2/3/4/.
Here's one option using regexp:
select *
from yourtable
where path regexp '1/[0-9]/[0-9]/$'
SQL Fiddle Demo
There are several ways to do that:
MySQL LIKE operator.
The LIKE operator provides two wildcard characters, the percentage % ( match any string of zero or more characters), and underscore _ ( match any single character ).
SELECT * FROM `table` WHERE `path` LIKE '1/_/_/'
SELECT * FROM `table` WHERE `path` LIKE '1/%/%/'
MySQL Regular Expressions.
SELECT * FROM `table` WHERE `path` regexp '^1/[0-9]/[0-9]/$'
Hierarchical Data in MySQL
Since this structure involves hierarchical data maybe you should consider to change the table structure to something that represents actual hierarchy. http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ has an excellent tutorial about the subject.

MySQL Query Anomaly

i faced a unique problem by accident
But before that i want to show you a table structure
td_category
|---------------------------------------------------------------------|
| category_id | category_title | category_slug | p_cid |
|---------------------------------------------------------------------|
| 1 | Shirts | 1-Shirts | 0 |
|---------------------------------------------------------------------|
| 2 | Jeans | 2-Jeans | 0 |
|---------------------------------------------------------------------|
Now,
category_id is INT and auto-increment value
category_title is VARCHAR
category_slug is VARCHAR
Now what i amdoing is that, by mistake i wrote a query
SELECT * FROM td_category WHERE category_id = '2-Jeans'
and instead of giving me any error it displayed the 2nd tuple
Isn't it supposed to throw an error??
please can anybody clarify?
mysql performs implicit conversion for int datatype due to which '2-Jeans' is treated as 2-0 (since Jeans is not an int type and is defaulted to 0 for compatibility as described in the docs here)
Hence the final query as the parser interprets is as below:
SELECT * FROM td_category WHERE category_id = 2;
The following query will take id as 2 which is your first character and display second record
SELECT * FROM td_category WHERE category_id = '2-Jeans'
Try this query which will return first record
SELECT * FROM td_category WHERE category_id = '1-Jeans'
2-jeans is treated as 2 so return second record and 1-jeans is treated as 1 so return first record.
Check Manual for auto casting in mysql.

MySQL: Retrieving all fields SELECT * when one of the fields is binary and needs to HEX

I have a primary kew which is a binary(16) UUID in a field called binid.
I would like to get ALL columns including the binary id with a SELECT statement.
I know I can do "SELECT * FROM TABLE", but how to combine with HEX(binid)?
This works when I get individual fields: "SELECT HEX(binid) AS binid FROM TABLE"
but I dont want to mention all of the fields (too many). Is there a way to get ALL and HEX in one statement?
PS. I am creating based on stackoverflow question: How to store uuid as number?
Selecting * will select all the fields as they are, without transformations. To select them changing their formats you will have to specify all the fields you want to select spearated by ,.
For instance:
SELECT HEX(`binid`) as `bindid`, `name`, FROM_UNIXTIME(`birthday`) as `birthday`, `gender` FROM `table`;
You can apply as many transformations you want.
You can also do this:
SELECT HEX(`binid`) as `hexdid`, * FROM `table`;
In this case the result will have both the binid in hex format, named hexid, and also the original binid aswell with the other fields of the table.
select col1, col2, col3 from table
e.g. if table is called T and set as thus:
T
=================
| binid | A | B |
| 0 | 1 | a |
| 1 | 2 | b |
| 10 | 3 | c |
select hex(binid), A, B from table
You could do:
Select *, HEX(binid) as clearBinId from Table
This will select all the columns (including binid) and also select the HEX(binid) as a column called 'clearBinId'

MySQL : interval around id column and return another one from subquery with multiple columns

I would like to run a query from a table where the content is like that :
id | col1 | col2 | col3
-----------------------
1 | i_11 | i_12 | i_13
2 | i_21 | i_22 | i_23
3 | i_31 | i_32 | i_33
.. | ... | ... | ...
SELECT col1 FROM table WHERE id IN
(SELECT id-1, id+1 FROM table WHERE col1='xxx' AND col2='yyy' AND col3='zzz')
The aim is to get an interval [id-1, id+1] based on the id column which returns the content stored in col1 for id-1 and id+1. The subquery works but I guess I have a problem with the query itself, since I'm having an error "Operand should contain only one column". I understand it, but I don't see any other way to do it in one query ?
I'm quite sure there's a pretty easy solution but I can't figure it out for the moment, even after having carefully read other posts about multiples columns' subqueries...
Thank you for any help :-)
The only way I can think to do it right now is like this:
SELECT col1
FROM table T
WHERE id BETWEEN (SELECT id FROM table WHERE col1='xxx' AND col2='yyy' AND col3='zzz') -1
and (SELECT id FROM table WHERE col1='xxx' AND col2='yyy' AND col3='zzz') +1
Your problem is that you are retrieving two values - but as a list rather than a set. The SQL optimizer can't see 1,3 as a set of two items when they are presented in a single row. There may also be a cast needed.
This should work.
SELECT col1 FROM table WHERE id in
(
select cast(id as int) -1 from table where col1='i_21'
union
select cast(id as int) +1 from table where col1='i_21'
)