简体   繁体   中英

How can i make inverse of IN Syntax?

IF I have a code like

$vals = "50,60,40";

IN SQL

"SELECT * FROM TABLE WHERE col IN( $vals )"

No if i have a value like 50 and i have col in SQL contain "50,40,60"

How can i selected it

I mean the inverse of IN Syntax

if i have table in sql contain values like

Firstname | Lastname | Age | Hobbies
Ahmed     | Ali      | 50  | run,swim
Mohammed  | Ahmed    | 30  | run

and if i want who can swimming in Hobbies

I mean the inverse of IN Syntax

You could use the

NOT IN

operator if you had a good table structure.

You should make a table for the Hobbies and then add a relanshionship with your person table, baecause as now the only way to get this done is with an ugly SQL containing lot of LIKE condition.

I recommend changing your schema to store the values in a separate table with a FK to the original column.

 People
 ID - PK
 FirstName
 LastName 

 Hobbies
 ID -- PK
 Person_ID -- FK to People
 Hobby -- store your comma-separated values here

Then you can do

select People.ID, People.FirstName, People.LastName
from People
   inner join Hobbies on People.ID = Hobbies.Person_ID
where Hobbies.Hobby = 'Swimming'

An even better structure might have 3 tables, allowing you to maintain a set of hobbies independently of the people and simply keeping a relation between each person and their hobbies.

People
ID 
FirstName
LastName

Hobbies
ID
Hobby

PeopleHobbies
ID
Person_ID
Hobby_ID

As always, consider your query needs and create suitable indices on the tables to allow speedy lookups and joins.

Check the FIND_IN_SET() function:

"SELECT * FROM TABLE WHERE FIND_IN_SET('swim', Hobbies) > 0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM