On 2015-09-16 08:27 PM, Nicolas J?ger wrote: > Hi guys, > > so there is the two ways I made: > > FIRST ONE: > ========== > > ** Create a table wich will store the result of EXISTS, > > CREATE TABLE _TAG_EXISTS_RESULT_( NAME, BOOL ); > > > ** The next query has to INSERT 'evil little sister' with BOOL to 1 in > _TAG_EXISTS_RESULT_ if 'evil little sister' is already present in TAGS, > > INSERT INTO _TAG_EXISTS_RESULT_ ( NAME, BOOL ) > SELECT 'evil little sister' > , EXISTS (SELECT 1 FROM TAGS WHERE NAME='evil little sister'); > > > ** Then I add 'evil little sister' if _TAG_EXISTS_RESULT_.BOOL = 0.. > > INSERT INTO TAGS (NAME, COUNT) > VALUES( > CASE ( SElECT BOOL FROM _TAG_EXISTS_RESULT_ ) WHEN 0 > THEN ( SElECT NAME FROM _TAG_EXISTS_RESULT_ ) > ELSE '$NOT_USED$' > END > , 0 ); > > ** delete $NOT_USED$ if so, > > DELETE FROM TAGS WHERE NAME='$NOT_USED$'; > > > ** Then, clear _TAG_EXISTS_RESULT_, > > DELETE FROM _TAG_EXISTS_RESULT_; > > > SECOND ONE: > ========== > > ** I made a compact version, > > INSERT INTO TAGS (NAME, COUNT) > VALUES > ( > CASE( SELECT EXISTS( SELECT 1 FROM TAGS WHERE NAME='evil little > sister' ) ) WHEN 0 > THEN 'evil little sister' > ELSE '$NOT_USED$' > END > , 1 > ); > > > ** delete $NOT_USED$ if so, > > DELETE FROM TAGS WHERE NAME='$NOT_USED$'; > > > comments are welcome.
It's hard to know where to begin. This looks much more like programming code than SQL - and while there are similarities, the usage is very different. Let me start with explaining the first and most important difference: Most programming languages are imperative (methodical or executive) descriptors - i.e you tell the process/engine/compiler HOW to achieve a task (which seems a bit like what you are trying to do up above). SQL is really a declarative language, i.e. you tell the process/engine WHAT you need, and it will figure out HOW to achieve that in the best and most efficient way. Of course, that is easier said than done, but we've all started with little things and built on from there. Very soon you will see how you can create a schema and some queries to achieve data-handling tasks that used to take you ages to program (at least, that's how it happened for me). To get you started on this road, may I ask you take a leap of faith and explain to us from A to Z what you would like to achieve with the tables and data you are asking about above - i.e don't show us the programming you think will solve the problem and ask us if that is good SQL, rather explain us the problem to be solved and allow us to show you the good SQL that will do it. Every next task should be clearer and easier. Cheers, Ryan