user2709752
user2709752

Reputation: 488

How to fetch primarykey from table based on a condition?

+----+------+
| 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.

Upvotes: 1

Views: 124

Answers (3)

Sohail
Sohail

Reputation: 574

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';

Upvotes: 1

RGO
RGO

Reputation: 4737

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.

Upvotes: 0

Donn Bly
Donn Bly

Reputation: 74

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.

Upvotes: 3

Related Questions