DELETE from same table used in the WHERE - mariadb

I have the following query that is supposed to delete from a table with a circular FK requirement;
DELETE FROM question
WHERE defaultGotoQuestionId IN (
SELECT id from question WHERE facilityId IN (
SELECT id FROM facility WHERE customerId NOT IN (1,76)
)
);
But I get the following error;
Table is specified twice, both as a target for 'DELETE' and as a separate source for data
I understand the error message - that I can't DELETE from a TABLE that I am specifying in the WHERE - I just can't seem to work out how to solve it, for myself.
I saw a few examples of using a join - but perhaps I am having an off day - because I have been iterating through copy/paste examples - but still can't manage it.
It works as a SELECT : In that the result gives me the records I want to delete;
SELECT id FROM question
WHERE defaultGotoQuestionId IN (
SELECT id from question WHERE facilityId IN (
SELECT id FROM facility WHERE customerId NOT IN (1,76)
)
);
Thanks for any help!

What version of MariaDB are you using?
DELETE :: Same Source and Target Table
Until MariaDB 10.3.1, deleting from a table with the same source and target was not possible. From MariaDB 10.3.1, this is now possible.
See dbfiddle.
In older versions of MariaDB (or in MySQL, for example), one option you can use is:
DELETE
`question`
FROM
`question`
INNER JOIN (
SELECT
`id`
FROM
`question`
WHERE
`defaultGotoQuestionId` IN (
SELECT
`id`
FROM
`question`
WHERE
`facilityId` IN (
SELECT
`id`
FROM
`facility`
WHERE
`customerId` NOT IN (1, 5)
)
)
) `der` ON
`question`.`id` = `der`.`id`;
See dbfiddle.

Related

Sqlite update with inner query select

According to all examples my query should be executing. I am trying to update new column on my table with the last 4 digits of the phone number like so :
UPDATE users
SET users.phone_last_4 = t.lastFour
FROM
(
select substr( phone_number, -4) as lastFour from users
) t;
Also tried this:
UPDATE users
SET users.phone_last_4 = t.lastFour
FROM
(
select substr( phone_number, -4) as lastFour from users
) AS t;
Both fail with same error :
near ".": syntax error: UPDATE users
SET users.
What could I possibly do wrong here?
SQLite does not support joins for the UPDATE statement and also this syntax containing FROM .
In your case I can't see why you need it.
Just do:
UPDATE users
SET phone_last_4 = substr(phone_number, -4)

how to update table with join?

In oracle db i have a table which include 2 varchar columns - new_val, old_val.
I need to update multiple tables which has several columns which include in their values the old_val from the 1st table mension above, and replace them with "new_val" from that table.
tried to perform the following but got an error:
UPDATE (SELECT a.account_id, b.new_val, b.old_val FROM
any_table a JOIN val_table b ON a.account_id like
'%'||b.old_val||'%') SET account_id=
replace(account_id,old_val ,new_val);
Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
I understand the error but can't find the proper solution.
Thanks,
Try:
UPDATE ANY_TABLE a
SET account_id= (
SELECT replace(a.account_id,b.old_val ,b.new_val)
FROM VAL_TABLE b
WHERE a.account_id like '%'||b.old_val||'%'
)
WHERE EXISTS (
SELECT 1 FROM VAL_TABLE b
WHERE a.account_id like '%'||b.old_val||'%'
);

Recursive Query CTE in SQL Lite

I have the Following table Structure. (I am new to SQL Lite)
create table Relations
(
Code int,
ParentCode int ,
fname text
)
GO
insert into Relations values(1,null,'A');
insert into Relations values(2,null,'B');
insert into Relations values(3,2,'C');
insert into Relations values(4,3,'D');
I want to get the initial parent of Code =4 :
i.e. values 2 null B
I am not able to figure out how to write a recursive query in sqllite.
Thanks in Advance..
Was a version issue..
This query was not working & was getting a syntax Error.
I upgraded From 3.7.17 To 3.8.7.4 version & it worked..
WITH RECURSIVE
works(Code,Parent) AS (
Select Code,ParentCode from Relations a where a.Code=4
UNION
SELECT Relations.Code, Relations.ParentCode FROM Relations , works
WHERE Relations.Code=works.Parent
)
SELECT * FROM works where Parent is null

Where-Condition as IN(Subquery) with Doctrine2 in Symfony2.3.1 doesnt work

---- Done with Symfony2.3.1 and Doctrine2 ----
Sorry, i hope i was not too stupid to find a suitable solution for my problem. I try to build a Query for hours.
SELECT * FROM product
WHERE product_id in
(
SELECT product_id from (
SELECT count(*) as result_amount, product_id FROM product_x_attribut
JOIN productattribut on productattribut_id = productattribut.id
WHERE (
productkey = "price" and
stringType = "premium"
) or (
productkey = "size" and
stringType = "S"
)
GROUP BY product_id
HAVING result_amount = 2
) as temp
)
GROUP BY product_id
ORDER BY p0_.name ASC
This is the SQL which works fine in phpmyAdmin.
This can be seen like
Select * from abc where abc.x in ( Select * from ( select * from ) as abcd )
So there is one core query, i call it subSubQuery, the second query around the core will be called subQuery and the outer Query is just the outer Query, no a Subquery.
I could build the subSubQuery with Doctrine2.
But i cannot built the subQuery like this
Select product_id from ( $subSubQuery->getQuery()->getDQL() )
I want to do the subQuery like this
$subQuery = $repositoryProduct->createQueryBuilder('product');
$subQuery->add('select', 'product_id');
$subQuery->add('from',$subSubQuery->getDQL() );
// However to set an alias is a miracle for me, this didnt work off course
$subQuery->add('as','tmp' );
This is the subQuery.
I also cannot build the outer Query
Select * from abc where abc.x in ( $subQuery->getQuery()->getDQL() )
I want to do this like this
$query->where(
$query->expr()->in('product.id', $subQuery->getDQL() )
);
But i try to build this with Doctrine2 like this:
I am so down, i tried ->getSQL(), ->getDQL(), i tried as much as i was able to detect as a suitable tiny step to a solution for this problem and i has tried as much keyword in google as my finger were able to write... I hope someone could help me to find a solution...
Thanks a lot to each helpful advise.
I know that statements like this work:
$qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL()));
Your question is kind of hard to follow. Consider using pastebin to show all your mappings as they currently exist. And then maybe presenting a simplieid query?
My $qbGameId query was built with:
$qbGameId = $em->createQueryBuilder();
$qbGameId->addSelect('distinct gameGameId.id');
$qbGameId->from('ZaysoCoreBundle:Event','gameGameId');
// Assorted joins and where conditions

sqlite3 if exists alternative

I am trying to run simple query for sqlite which is update a record if not exists.
I could have used Insert or replace but article_tags table doesn't have any primary key as it is a relational table.
How can I write this query for sqlite as if not exists is not supported.
And I don't have idea how to use CASE for this ?
Table Structure:
articles(id, content)
article_tags(article_id, tag_id)
tag(id, name)
SQLITE Incorrect Syntax Tried
insert into article_tags (article_id, tag_id ) values ( 2,7)
if not exists (select 1 from article_tags where article_id =2 AND tag_id=7)
I think the correct way to do this would be to add a primary key to the article_tags table, a composite one crossing both columns. That's the normal way to do many-to-many relationship tables.
In other words (pseudo-DDL):
create table article_tags (
article_id int references articles(id),
tag_id int references tag(id),
primary key (article_id, tag_id)
);
That way, insertion of a duplicate pair would fail rather than having to resort to if not exists.
This seems to work, although I will, as others have also said, suggest that you add some constraints on the table and then simply "try" to insert.
insert into article_tags
select 2, 7
where not exists ( select *
from article_tags
where article_id = 2
and tag_id = 7 )

Resources