I have two table category and subcategory
I am trying to delete record from this table using mysql query
Query is=
$sql="Delete t1, t2 From category as t1
INNER JOIN subcategory as t2 on t1.c_id = t2.c_id
WHERE t1.c_id='$del_c_id' ";
This query only delete row from category(t1) whose primary key used into subcategory(t2) table.
Not delete row from category(t1) whose primary key not used in subcategory(t2).
You need to use a LEFT JOIN instead of INNER JOIN. By definition LEFT JOIN returns all results from t1, even if they don't have a match in t2.
See this link for more info on join types:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
Try CASCADE option in mysql. Subcategory will be deleted automatically if you delete the category. You need to use the InnoDB storage engine to use this feature.
Here is the accepted answer
Related
So I have three tables. I want the first table to match the third table based on their matching ids. Afterwards, I want the third table's id to be replaced by the second table's id (concat'd with a 'g' in front), which is identified through a select query on the first and second table.
Here's my rough idea of how it should go, just not too sure of how to match, then use tbl2's id:
UPDATE tbl3 SET col=CONCAT('g',tbl2.id) WHERE
id IN (
SELECT tbl1.id, tbl2.id FROM tbl1 left join tbl2 on tbl1.id = tbl2.id
WHERE blah='blah');
Is this possible in MySQL alone or will I have to do it in php using multiple queries?
So I found a MySQL fiddle site. Not bad, but doesn't allow UPDATE. Anyway, at least you can see the SELECT working:
http://sqlfiddle.com/#!9/bfdb66/7
Here's the SQL:
UPDATE tbl3 t3
LEFT JOIN tbl1 t1 ON t3.id=t1.id
LEFT JOIN tbl2 t2 ON t2.id=t1.id
SET t3.col=CONCAT('g',t2.id) WHERE
t3.blah = 'blah' AND t2.id IS NOT NULL;
According to this spec:
I want the first table to match the third table based on their matching ids
I want the third table's id to be replaced by the second table's id
which is identified through a select query on the first and second table
Let me know if I've misunderstood!
I am trying to join two tables together in a view. My first table combines two tables but now I am trying to join that table to a second table. I am trying to use a join to make sure the second table which contains roles which are performed by the user, matches up with the first table but if there are no records in the second table, I still want all the records from table 1. I know my explanation is a little confused, so my code is as follows:
CREATE VIEW `data` AS SELECT
`information`.`username`, `information`.`department`,
`information`.`company`, `information`.`title`,
`information`.`internal_number` AS `user_internal_phone`,
`information`.`external_number`AS `user_external_phone`,
`information`.`mail`, `information`.`cn` AS `name`, `information`.`hours`,
`information`.`languages`, `information`.`functions`,
`information`.`service` AS `contact_point_name_one`,
`information`.`subservice` AS `contact_point_name_two`,
`information`.`internal_phone` AS `contact_internal_phone`,
`information`.`external_phone` AS `contact_external_phone`,
`information`.`keywords`, `information`.`description`,
`information`.`provided_by`, `information`.`id`,
GROUP_CONCAT(`staff_roles`.`role` SEPARATOR ', ') AS `roles`,
`staff_roles`.`user`
FROM `information`
CROSS JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
I get an error when I do an outer join and a cross join and an inner join both return rows where there is a row in both tables yet I want it to display the rows where there is nothing in the second table as well. The purpose of using a join is so that, where there is a match, the row from table 2 should match the row on table 1
Use LEFT JOIN. The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
Just replace your CROSS JOIN with LEFT JOIN
Simply use LEFT JOIN instead of CROSS JOIN:
CREATE VIEW `data` AS SELECT
...
FROM `information`
LEFT JOIN `staff_roles` ON `information`.`username` = `staff_roles`.`user`;
Take a look at http://www.w3schools.com/sql/sql_join_left.asp for further details about why LEFT JOIN.
I'm doing some maintenance work on a database application and I've discovered that, joy of joys, even though values from one table are being used in the style of foreign keys, there's no foreign key constraints on the tables.
I'm trying to add FK constraints on these columns, but I'm finding that, because there's already a whole load of bad data in the tables from previous errors which have been naively corrected, I need to find the rows which don't match up to the other table and then delete them.
I've found some examples of this kind of query on the web, but they all seem to provide examples rather than explanations, and I don't understand why they work.
Can someone explain to me how to construct a query which returns all the rows with no matches in another table, and what it's doing, so that I can make these queries myself, rather than coming running to SO for every table in this mess that has no FK constraints?
Here's a simple query:
SELECT t1.ID
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
The key points are:
LEFT JOIN is used; this will return ALL rows from Table1, regardless of whether or not there is a matching row in Table2.
The WHERE t2.ID IS NULL clause; this will restrict the results returned to only those rows where the ID returned from Table2 is null - in other words there is NO record in Table2 for that particular ID from Table1. Table2.ID will be returned as NULL for all records from Table1 where the ID is not matched in Table2.
I would use EXISTS expression since it is more powerful, you can e.g. more precisely choose rows you would like to join. In the case of LEFT JOIN, you have to take everything that's in the joined table. Its efficiency is probably the same as in the case of LEFT JOIN with null constraint.
SELECT t1.ID
FROM Table1 t1
WHERE NOT EXISTS (SELECT t2.ID FROM Table2 t2 WHERE t1.ID = t2.ID)
SELECT id FROM table1 WHERE foreign_key_id_column NOT IN (SELECT id FROM table2)
Table 1 has a column that you want to add the foreign key constraint to, but the values in the foreign_key_id_column don't all match up with an id in table 2.
The initial select lists the ids from table1. These will be the rows we want to delete.
The NOT IN clause in the where statement limits the query to only rows where the value in the foreign_key_id_column is not in the list of table 2 ids.
The SELECT statement in parenthesis will get a list of all the ids that are in table 2.
Let we have the following 2 tables(salary and employee)
Now i want those records from employee table which are not in salary.
We can do this in 3 ways:
Using inner Join
select * from employee
where id not in(select e.id from employee e inner join salary s on e.id=s.id)
Using Left outer join
select * from employee e
left outer join salary s on e.id=s.id where s.id is null
Using Full Join
select * from employee e
full outer join salary s on e.id=s.id where e.id not in(select id from salary)
Where T2 is the table to which you're adding the constraint:
SELECT *
FROM T2
WHERE constrained_field NOT
IN (
SELECT DISTINCT t.constrained_field
FROM T2
INNER JOIN T1 t
USING ( constrained_field )
)
And delete the results.
From similar question here MySQL Inner Join Query To Get Records Not Present in Other Table I got this to work
SELECT * FROM bigtable
LEFT JOIN smalltable ON bigtable.id = smalltable.id
WHERE smalltable.id IS NULL
smalltable is where you have missing records, bigtable is where you have all the records. The query list all the records that not exist in smalltable but exists on the bigtable. You could replace id by any other matching criteria.
I Dont Knew Which one Is Optimized (compared to #AdaTheDev
) but This one seems to be quicker when I use (atleast for me)
SELECT id FROM table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2
If You want to get any other specific attribute you can use:
SELECT COUNT(*) FROM table_1 where id in (SELECT id FROM table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2);
You could opt for Views as shown below:
CREATE VIEW AuthorizedUserProjectView AS select t1.username as username, t1.email as useremail, p.id as projectid,
(select m.role from userproject m where m.projectid = p.id and m.userid = t1.id) as role
FROM authorizeduser as t1, project as p
and then work on the view for selecting or updating:
select * from AuthorizedUserProjectView where projectid = 49
which yields the result as shown in the picture below i.e. for non-matching column null has been filled in.
[Result of select on the view][1]
You can do something like this
SELECT IFNULL(`price`.`fPrice`,100) as fPrice,product.ProductId,ProductName
FROM `products` left join `price` ON
price.ProductId=product.ProductId AND (GeoFancingId=1 OR GeoFancingId
IS NULL) WHERE Status="Active" AND Delete="No"
SELECT * FROM First_table
MINUS
SELECT * FROM another
How to select rows with no matching entry in Both table?
select * from [dbo].[EmppDetails] e
right join [Employee].[Gender] d on e.Gid=d.Gid
where e.Gid is Null
union
select * from [dbo].[EmppDetails] e
left join [Employee].[Gender] d on e.Gid=d.Gid
where d.Gid is Null
Please, could you help me, how to delete data from more than 1 table in just one query?
I have this tables structure:
products
texts
files
products_files - here are mapped files to products - product_id, file_id
texts_files - here are mapped files to texts - text_id, file_id
And I need to do this:
If I delete file with id 50, I need to delete all rows from products_files and texts_files where file_id = 50.
Do you know, how to do it?
I tried to use left join, but without any results...
$query = 'DELETE products_files, texts_files FROM products_files
LEFT JOIN texts_files ON texts_files.file_id = products_files.file_id
WHERE products_files.file_id = '.$id.' OR texts_files.file_id = '.$id.'';
You might need ON DELETE CASCADE functionality. However, use it with care as it might have surprising consequences:
http://www.mysqltutorial.org/mysql-on-delete-cascade/
If you add ON DELETE CASCADE in your create table-query, you can delete any item from it. If there are any foreign key constraints, mysql automatically follows the connection and also deletes entries in the other table.
If you wanna stay on the safe side though (recommended), you will need to use multiple delete statements.
you can specify which table to delete from by prefixing a * with the table name: DELETE table.* FROM table1 JOIN table2 JOIN ... WHERE ... The WHERE clause specifies which rows to delete.
Try this:
DELETE f1,f2
FROM products_files f1
INNER JOIN texts_files f2 ON f1.file_id = f2.file_id
WHERE f1.file_id = '.$id.';
OR
use MySQL Foreign Key constraints
MySQL foreign key constraints, cascade delete
Essentially your query seems fine to me (except for the LEFT JOIN) - does this not work...
DELETE pf
, tf
FROM products_files pf
JOIN texts_files tf
ON tf.file_id = pf.file_id
WHERE pf.file_id = $id;
I am trying to delete record from 3 tables in 1 sql query in php. First, I tried it with delete records from two tables. This is the query for that:
DELETE pa, pr FROM pollanswers pa INNER JOIN pollresults pr ON
pa.PollQuestionId=pr.PollQuestionId WHERE pa.PollQuestionId = '123';
The problem is, what if there is no PollQuestionId in one of these table.. And other thing after that how to integrate it with third table?
Thanks.
You should not delete from multiple tables in one query.
You can define foreign key constraints on the tables with ON DELETE CASCADE option.
Then deleting the record from parent table removes the records from child tables.
Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
I have figured it out guys.. Thanks for your effort...
here is the query to join 3 tables:
DELETE po, pa, pr FROM posts po
LEFT JOIN pollanswers pa ON pa.PollQuestionId=po.PostId
LEFT JOIN pollresults pr ON pr.PollQuestionId=po.PostId
WHERE po.PostId = '123';
To join a third table, you could add another inner join:
DELETE pa, pr FROM pollanswers pa
INNER JOIN pollresults pr ON pa.POllQuestionID=pr.PollQuestionId
INNER JOIN pollwhatevers pw ON pw.whatevercolumn=pa.PollquestionID
WHERE pa.PollQuestionId = '123';
But if you want to join it to a table that is the result of joining PollResults and PollAnswers, you may want to consider using a temporary table. See this link for more information,I'm not sure I can explain it as well as this does:
http://devzone.advantagedatabase.com/dz/webhelp/Advantage7.1/adssql/using_temporary_tables_in_sql_statements.htm