I am trying to delete values from two tables using an inner join. The problem I am having is I get the error 'Not unique table/alias'
So here are my two tables with example rows inserted
MemberShipCore
UserId
StartDate
EndDate
MemberShipId
4
2022-01-01
2024-01-01
4
MemberShipType
MemberShipId
Gym
Cardio
4
1
0
I am trying to delete both rows in one sql statement
The statement I have so far is this:
DELETE `UserId`, `StartDate`, `EndDate`, `MembersipCore`.`MemberShipId`, `MembershipType`.`MemberShipId`, `Gym`, `Cardio` FROM `MembershipType`, `MembershipCore` INNER JOIN `MembershipCore` ON `MemberShipType`.`MemberShipId` = `MembershipCore`.`MemberShipId`
When running this in phpmyadmin I am given the error message
Error
SQL query: Copy
DELETE `UserId`, `StartDate`, `EndDate`, `MembersipCore`.`MemberShipId`, `MembershipType`.`MemberShipId`, `Gym`, `Cardio` FROM `MembershipType`, `MembershipCore` INNER JOIN `MembershipCore` ON `MemberShipType`.`MemberShipId` = `MembershipCore`.`MemberShipId`;
MySQL said: Documentation
#1066 - Not unique table/alias: 'MembershipCore'
Related
My update query checks whether the column “Houses” is null in any of the rows in my source table by joining the id between the target & source table (check query one). The column Houses being null in this case indicates that the row has expired; thus, I need to expire the row id in my target table and set the expired date. The query works fine, but I was wondering if it can be improved; I'm new to SQL, so I don't know if using two joins is the best way to accomplish the result I want. My update query will later be used against millions of rows. No columns has been indexed yet.
Query:
(Query one)
Update t
set valid_date = GETDATE()
From Target T
JOIN SOURCE S ON S.ID = T.ID
LEFT JOIN SOURCE S2 ON S2.Houses = t.Houses
WHERE S2.Houses is null
Target:
ID
namn
middlename
Houses
date
1
demo
hello
2
null
2
demo2
test
4
null
3
demo3
test1
5
null
Source:
ID
namn
middlename
Houses
1
demo
hello
null
3
demo
world
null
Expected output after running update query :
ID
namn
middlename
Houses
date
1
demo
hello
2
2022-12-06
2
demo2
test
4
null
3
demo3
test1
5
2022-12-06
I would recommend exists:
update t
set valid_date = getdate()
from target t
where exists (select 1 from source s where s.id = t.id and s.houses is null)
Note that your original query does not exactly do what you want. It cannot distinguish source rows that do not exist from source rows that exist and whose houses column is null. In your example, it would update row 2, which is not what you seem to want. You would need an INNER JOIN instead of the LEFT JOIN.
With EXISTS, you want an index on source(id, houses) so the subquery can execute efficiently against target rows. This index is probably worthwhile for the the JOIN as well.
I don't see why you'd need to join on the column houses at all.
Find all rows in source that have value NULL in the column houses.
Then update all rows in target that have the IDs of the source rows.
I prefer to write these kind of complex updates using CTEs. It looks more readable to me.
WITH
CTE
AS
(
SELECT
Target.ID
,Target.Date
FROM
Source
INNER JOIN Target ON Target.ID = Source.ID
WHERE Source.Houses IS NULL
)
UPDATE CTE
SET Date = GETDATE();
To efficiently find rows in source that have value NULL in the column houses you should create an index, something like this:
CREATE INDEX IX_Houses ON Source
(
Houses
);
I assume that ID is a primary key with a clustered unique index, so ID would be included in the IX_Houses index implicitly.
I have a query that joins 4 tables. It returns 35 rows every time I run it. Here it is..
SELECT Lender.id AS LenderId,
Loans.Loan_ID AS LoanId,
Parcels.Parcel_ID AS ParcelId,
tr.Tax_ID AS TaxRecordId,
tr.Tax_Year AS TaxYear
FROM parcels
INNER JOIN Loans ON (Parcels.Loan_ID = Loans.Loan_ID AND Parcels.Escrow = 1)
INNER JOIN Lender ON (Lender.id = Loans.Bank_ID)
INNER JOIN Tax_Record tr ON (tr.Parcel_ID = Parcels.Parcel_ID AND tr.Tax_Year = :taxYear)
WHERE Loans.Active = 1
AND Loans.Date_Submitted IS NOT NULL
AND Parcels.Municipality = :municipality
AND Parcels.County = :county
AND Parcels.State LIKE :stateCode
If I left join a table (using a subquery in the on clause of the join), MySQL does some very unexpected things. Here's the modified query with the left join...
SELECT Lender.id AS LenderId,
Loans.Loan_ID AS LoanId,
Parcels.Parcel_ID AS ParcelId,
tr.Tax_ID AS TaxRecordId,
tr.Tax_Year AS TaxYear
FROM parcels
INNER JOIN Loans ON (Parcels.Loan_ID = Loans.Loan_ID AND Parcels.Escrow = 1)
INNER JOIN Lender ON (Lender.id = Loans.Bank_ID)
INNER JOIN Tax_Record tr ON (tr.Parcel_ID = Parcels.Parcel_ID AND tr.Tax_Year = :taxYear)
LEFT OUTER JOIN taxrecordpayment trp ON trp.taxRecordId = tr.Tax_ID AND trp.paymentId = (
SELECT p.id
FROM taxrecordpayment trpi
JOIN payments p ON p.id = trpi.paymentId
WHERE trpi.taxRecordId = tr.Tax_ID AND p.isFullYear = 0
ORDER BY p.dueDate, p.paymentSendTo
LIMIT 1
)
WHERE Loans.Active = 1
AND Loans.Date_Submitted IS NOT NULL
AND Parcels.Municipality = :municipality
AND Parcels.County = :county
AND Parcels.State LIKE :stateCode
I would like to note that the left join table does not appear in the where clause of the query at all, and I am not using the left join table in the select clause. In real life, I actually use the left join records in the select clause, but in my effort to get to the essential elements causing this problem, I have simplified the query and removed everything but the essential parts that cause trouble.
Here's what is happening...
Where I used to get 35 records, now I get a random number of records approaching 35. Sometimes, I get 33. Other times, I get 27, or 29, or 31, and so on. I would never expect a left join like this to filter out any records from my result set. A left join should only add additional columns to the result set, particularly when - as is the case here - the left join table is not part of the where clause.
I have determined that the problem really only happens if the subquery has a non-deterministic sort. In other words, if I have two taxrecordpayment records that match the subquery and both have the same due date and the same "paymentSendTo" value, then I see the issue. If the inner subquery has a deterministic sort, the issue goes away.
I would imagine that some people will look at my simplified example and recommend that I simply remove the subquery. If my query were this simple in real life, that would be the way to go.
In reality, the entire query is more complicated, is hitting a LOT of data, and modifying it is possible, but costly. Removing the subquery is even more costly.
Has anyone seen this sort of behavior before? I would expect a non-deterministic subquery to simply produce inconsistent results and I would never expect a left join like this to actually filter records out when the left joined table is not used at all in the where clause.
Here is the query plan, as provided by EXPLAIN...
id
select_type
table
partitions
type
possible_keys
key
key_len
ref
rows
filtered
Extra
1
PRIMARY
parcels
NULL
range
PRIMARY,Loan_ID,state_county,ParcelsCounty,county_state,Location,CountyLoan
county_state
106
NULL
590
1
Using index condition; Using where
1
PRIMARY
tr
NULL
eq_ref
parcel_year,ParcelsTax_Record,Year
parcel_year
8
infoexchange.parcels.Parcel_ID,const
1
100
Using index
1
PRIMARY
Loans
NULL
eq_ref
PRIMARY,Bank_ID,Bank,DateSub,loan_number
PRIMARY
4
infoexchange.parcels.Loan_ID
1
21.14
Using where
1
PRIMARY
Lender
NULL
eq_ref
PRIMARY
PRIMARY
8
infoexchange.Loans.bank_id
1
100
Using index
1
PRIMARY
trp
NULL
eq_ref
taxRecordPayment_key,IDX_trp_pymtId_trId
taxRecordPayment_key
8
infoexchange.tr.Tax_ID,func
1
100
Using where; Using index
2
DEPENDENT SUBQUERY
trpi
NULL
ref
taxRecordPayment_key,IDX_trp_pymtId_trId
taxRecordPayment_key
4
infoexchange.tr.Tax_ID
1
100
Using index; Using temporary; Using filesort
2
DEPENDENT SUBQUERY
p
NULL
eq_ref
PRIMARY
PRIMARY
4
infoexchange.trpi.paymentId
1
10
Using where
I have attempted to recreate this with a contrived data setup and an analogous query, but with my contrived data set, I cannot get the subquery behave non-deterministically even though it suffers from the same problem as my subquery above (there are multiple records that match the subquery and the order by is not unique for those records).
This seems to require a massive data set to start misbehaving. It happens on multiple distinct instances of MySQL 5.7, while a MySQL 5.6 instance does not demonstrate the problem at all. I am hoping someone can spot something in the above query plan to help me understand why the subquery is non-deterministic and - more importantly - why that causes records to get dropped from the result set.
I feel like this is either a data set issue (perhaps we need to do a table optimize or do some maintenance on our tables), or a bug in MySQL.
I have submitted a bug for this behavior.
https://bugs.mysql.com/bug.php?id=104824
You can recreate this behavior as follows...
CREATE TABLE tableA (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10)
);
CREATE TABLE tableB (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
tableAId INTEGER NOT NULL,
name VARCHAR(10),
CONSTRAINT tableBFKtableAId FOREIGN KEY (tableAId) REFERENCES tableA (id)
);
INSERT INTO tableA (name)
VALUES ('he'),
('she'),
('it'),
('they');
INSERT INTO tableB (tableAId, name)
VALUES (1, 'hat'),
(2, 'shoes'),
(4, 'roof');
Run this query multiple times and the number of rows returned will vary:
SELECT COALESCE(b.id, -1) AS tableBId,
a.id AS tableAId
FROM tableA a
LEFT JOIN tableB b ON (b.tableAId = a.id AND 0.5 > RAND());
I have an SQL database (pq) with 3 tables as sample is shown in image. I am trying to achieve below things:
Select only rows with variable P from the MEASUREMENT column in Table 3. I tried below query but it didnt produced the correct output.
select distinct pq_data.READ_TIME,OBS_METER,MEASUREMENT,VALUE from pq_data ORDER BY MEASUREMENT;
Then, fetch the data columns CUST_CLASS, and SOLAR from Table 1 into Table 3 according to OBS_METER id. The OBS_METER column is not available in Table 1 but the it can be obtained from OBS_LOCATION in Table 2.
The expected output of SQL query is Table 3 with additional columns from other tables,such as:
row id READ_TIME OBS_METER OBS_LOCATION MEASUREMENT VALUE CUST_CLASS SOLAR
28/01/2018 2018/01/28 01:55:00 105714 6787 P 284 R F
..........
I searched for existing answers: 1 , 2 but I couldnt able to write a SQL query which will produce above expected output.
Select only rows with variable P from the MEASUREMENT column in Table 3.
select * from pq_data WHERE MEASUREMENT='P';
Then, fetch the data columns CUST_CLASS, and SOLAR from Table 1 into
Table 3 according to OBS_METER id.
select *
from pq_data pd
inner join meter_mapping mm on pd pd.obs_meter=mm.obs_meter
inner join location_mapping lm on mm.obs_location=lm.obs_location
WHERE pd.MEASUREMENT='P'
The expected output of SQL query is Table 3 with additional columns
from other tables:
You did not specify which table is the rowid that you wanted, I assumed that it was from pq_data.
Also, I don't know if an entry on pq_data will always have a match in meter_mapping (and location_maping). If it don't you need to use "left join" (or right).
It would be easier if you used the actual name of the tables in your questions (instead of table 1, 2 and 3).
select pd.rowid, pd.READ_TIME, pd.OBS_METER, mm.OBS_LOCATION, pd.MEASUREMENT, pd.VALUE, lm.CUST_CLASS, lm.SOLAR
from pq_data pd
inner join meter_mapping mm on pd pd.OBS_METER=mm.OBS_METER
inner join location_mapping lm on mm.OBS_LOCATION=lm.OBS_LOCATION
WHERE pd.MEASUREMENT='P'
I'm writing a SQL script in Visual Studio and I have 2 tables, one called ATB which has unique rows for Account IDs and a second table that has AccountID too and another column called SettlementTypeID, this second column has duplicate values as it keeps a record of changes done on the AccountID which mean it can have 10 rows with the same AccountID but with a different Lastmodified date column.
I'm doing a join between them to get the SettlementTypeID for each AccountID on table ATB using the MAX(LastModifiedDate) to avoid getting the duplicate values but for some AccountIDs is not working at all
Below is my current Code:
SELECT
t.AccountID,
r.SettlementTypeID,
r.LastModifiedDate
FROM
(SELECT
accs.AccountID,
accs.SettlementTypeID,
MAX(accs.LastModifiedDate) AS LastModifiedDate
FROM
AccountSettlement accs
INNER JOIN
#ATB atb WITH (nolock) ON atb.AccountID = accs.AccountID
WHERE
atb.ReferenceType = 'Settlement'
AND atb.SettlementType IS NULL
GROUP BY
accs.AccountID, accs.SettlementTypeID) r
INNER JOIN
AccountSettlement t ON t.AccountID = r.AccountID
AND t.SettlementTypeID = r.SettlementTypeID
AND t.LastModifiedDate = r.LastModifiedDate
I do not know what am I doing wrong but when I remove the SettlementTypeID column and just leave the accountID and LastmodifiedDate columns it works as expected.
Below there is an small portion of what I'm getting:
And this is the data that the script should be providing based on the max date found:
Database: Oracle
I want to insert data from table 1 to table 2 but the catch is, primary key of table 2 is the combination of first 4 letters and last 4 numbers of the primary key of table 1.
For example:
Table 1 - primary key : abcd12349887/abcd22339887/abcder019987
In this case even if the primary key of table 1 is different, but when I extract the 1st 4 and last 4 chars, the output will be same abcd9887
So, when I use select to insert data, I get error of duplicate PK in table 2.
What I want is if the data of the PK is already present then don't add that record.
Here's my complete stored procedure:
INSERT INTO CPIPRODUCTFAMILIE
(productfamilieid, rapport, mesh, mesh_uitbreiding, productlabelid)
(SELECT DISTINCT (CONCAT(SUBSTR(p.productnummer,1,4),SUBSTR(p.productnummer,8,4)))
productnummer,
ps.rapport, ps.mesh, ps.mesh_uitbreiding, ps.productlabelid
FROM productspecificatie ps, productgroep pg,
product p left join cpiproductfamilie cpf
on (CONCAT(SUBSTR(p.productnummer,1,4),SUBSTR(p.productnummer,8,4))) = cpf.productfamilieid
WHERE p.productnummer = ps.productnummer
AND p.productgroepid = pg.productgroepid
AND cpf.productfamilieid IS NULL
AND pg.productietype = 'P'
**AND p.ROWID IN (SELECT MAX(ROWID) FROM product
GROUP BY (CONCAT(SUBSTR(productnummer,1,4),SUBSTR(productnummer,8,4))))**
AND (CONCAT(SUBSTR(p.productnummer,1,2),SUBSTR(p.productnummer,8,4))) not in
(select productfamilieid from cpiproductfamilie));
The highlighted section seems to be wrong, and because of this the data is not picking up.
Please help
Try using this.
p.productnummer IN (SELECT MAX(productnummer) FROM product
GROUP BY (CONCAT(SUBSTR(productnummer,1,4),SUBSTR(productnummer,8,4))))