SQL for checkboxes with a many-to-many relationship - sql

I have three tables.
Directors:
Directors
ID
First Name
Last Name
Films:
Films
Film ID
Title
Total
Directors-to-Films
Director-to-Films
Director ID
Film ID
The Directors-to-Films stores the ids like this:
Director ID Film ID
1 1
1 2
1 3
1 4
The films I list with checkboxes.
How do I do an SQL update so that the table looks like:
Director ID Film ID
1 1
1 3
(i.e. Films "2" and "4" are removed) OR
Director ID Film ID
1 1
1 2
1 3
1 4
1 5
(i.e. Film "5" is added to Director "1")?

Unless I'm missing something, the SQL you're looking for is just a delete and an insert:
delete Directors_to_Films where Director_ID = 1 and Film_ID in (2,4);
insert into Directors_to_Films (Director_ID, Film_ID) values (1,5);
This assumes that when you're creating the UI, that you are fetching the appropriate IDs and associating them to the controls.
To clarify the last statement: If I understand correctly, you're displaying the film, then a list of directors with check boxes next to their names. The user can check one or more of the boxes. if this is correct, then, presumably, you are retrieving the list of directors from the database. At the same time you should be retrieving the associated ID and storing it in a property of the check box. When it comes time to update the database, you ask the check-box control for that value to figure out which row of the database you're updating.

Related

Laravel 7 Select a record if the id dosen't exist in another table

Using laravel 7 i am trying to select an item record as long as that records id dosen't appear in another table but only as long as the id in the other table is accompanied by the users id
Item table
id
item name
Banned Items
ItemID
UserID
Edit 1
If an item is banned it its added to the banned items table that stores the item id and the user id when i load the items i need to exclude the items that appear in the banned items table but only for the user that is banned for
Items table
1 Apple
2 Pear
Banned Items
1 1
1 2
Users
1 username1 password1
2 username2 password2
so if the item is banned for that user don't select the item. I'm struggling to do this. Thanks
I didn't understand how did you create a relation between banned items and users, but you need that relation. So I assume the columns on banned_items table are
id, user_id, item_id
$bannedItems = BannedItem::where('user_id', Auth::id())->get()->pluck('id');
// If you don't have a model for pivot table:
$bannedItems = DB::table('banned_items')->where('user_id', Auth::id())->get()->pluck('id');
$items = Item::whereNotIn('id', $bannedItems)->get();
should return the items that weren't banned by the current user.

Querying SQL table with different values in same column with same ID

I have an SQL Server 2012 table with ID, First Name and Last name. The ID is unique per person but due to an error in the historical feed, different people were assigned the same id.
------------------------------
ID FirstName LastName
------------------------------
1 ABC M
1 ABC M
1 ABC M
1 ABC N
2 BCD S
3 CDE T
4 DEF T
4 DEG T
In this case, the people with ID’s 1 are different (their last name is clearly different) but they have the same ID. How do I query and get the result? The table in this case has millions of rows. If it was a smaller table, I would probably have queried all ID’s with a count > 1 and filtered them in an excel.
What I am trying to do is, get a list of all such ID's which have been assigned to two different users.
Any ideas or help would be very appreciated.
Edit: I dont think I framed the question very well.
There are two ID's which are present multiple time. 1 and 4. The rows with id 4 are identical. I dont want this in my result. The rows with ID 1, although the first name is same, the last name is different for 1 row. I want only those ID's whose ID is same but one of the first or last names is different.
I tried loading ID's which have multiple occurrences into a temp table and tried to compare it against the parent table albeit unsuccessfully. Any other ideas that I can try and implement?
SELECT
ID
FROM
<<Table>>
GROUP BY
ID
HAVING
COUNT(*) > 1;
SELECT *
FROM myTable
WHERE ID IN (
SELECT ID
FROM myTable
GROUP BY ID
HAVING MAX(LastName) <> MIN(LastName) OR MAX(FirstName) <> MIN(FirstName)
)
ORDER BY ID, LASTNAME

Database schema for Sales Commissions

I'm trying to create a database with table titles which contains different titles, code(short code for the name) and commission of that title on other titles for instance.
I have a table named Title
Id Name Code CommissionOnA CommissionOnEng
1 Admin A 0 15
2 Engineer Eng 1 0
Now Is it good to have table schema like this, as the titles will change and can be inserted, updated or deleted dynamically. So with my current approach I have to alter table and add another column to it, in order to add commission for new title.
Is there any better way to do it, considering in mind that this also support multilevel sale heirarchy. Schema for any database is fine, but for MySql is preferred.
The Scenerio is, that the form where user creates a new title, dynamically renders all the titles that exist in the table with the textbox, so that when user creates a new title, he should be able to add commissions corresponding to other titles for the new title.
for instance if user creates a new Title name "Consultant" with code "c", he should see textboxes for Admin, Engineer, so that when user saves it, a row in the table gets created which has following data
Id Name Code CommissionOnA CommissionOnEng CommissionOnC
1 Admin A 0 15 0
2 Engineer Eng 1 0 0
3 Consultant C 12 5 0
Now I have another table called Employees
Id Name Title ManagerId
1 Rob 1 Null
2 Kate 2 1
3 Eli 3 2
4 Al 2 3
Now when Ido recursion, each time a junior get sale, a commission should be transfered to his manager as well as manager of his manager based on the commission specified in the title table.
So, when Al sells something, than Eli should get commission of 5 as, title of Eli is Consultant and Eli is boss of Al, so Employee with title Consultant(3) get commission of 5, if Employee with title Engineer(2) sells something.
It's better to normalise your table schemas so you don't need to add new columns instead put those related columns into their own table and then join these records via a foreign key.
For example, create a new table named commissions, then have a column for its unique ID, the ID that relates to the titles table and the commission amount:
commissions
----------------------------
id (INT, NOT NULL, Primary Key)
titles_id (INT, NOT NULL)
amount (INT, NOT NULL, DEFAULT=0)
and the data would look like:
id titles_id amount
1 1 15
2 2 1

How do you Swap details in columns from one ID to another ID?

I have 3 tables, the person table, the organisation table and the link table
called PersonOrganisation with PersonId and Organisation keys. I want to
swap two people between two organisations after the User inputs the Id's of the two people he wants to switch.
Example: I enter 2 and 6 for the PersonId's
and then the organisation associated with person 2 is swapped with organisation associated with person 6.
Thanks in Advance
How about this:
update PersonOrganization
set PersonId = (case when PersonId = 2 then 6 else 2 end)
where (PersonId in (2, 6);
In other words, swap the persons, not the organizations.

sql insert and update question..multiple queries in one statement

I have a table called auctions, which has various columns such as username, auction id(the primary key), firstname, lastname, location etc, as well as a category column. The category column is blank by default, unless it is filled in for a particular record by a user.
I have made a new users table, which has username and category columns, as well as aditional fields which will be completed by user input.
I would like to know if it is possible when updating a record in the auctions table to have a category, to insert the username and category from that record into the users table as long as the username is not already present in the table.
For example, if I have the following tables:
auctions
auctionid username firstname lastname category
------------------------------------------------------------------------
1 zerocool john henry
2 fredflint fred smith
3 azazal mike cutter
Then, upon updating the second record to have a catagory like so:
2 fredflintsoner fred smith shoes
The resulting users table should be:
users
username shoes pants belts misc1 misc2
--------------------------------------------------
fredflint true
With no record have existed previously.
If additional auctions exist with the same username in the auctions table, such as:
7 fredflint fred smith belts
Then even if this auction is added to the category, a new record should not be inserted for the users table, as the username is already , however it should be updated as necessary, resulting in:
username shoes pants belts misc1 misc2
--------------------------------------------------
fredflint true true
What you are looking for is known as a TRIGGER. You can specify something to run after every insert/update in the auctions table and then determine what to do to the users table.
A couple of questions come to mind. The first is, your user table looks denormalized. What happens when you add a new category? Consider a user table in the form of:
id username category
Where you have multiple rows if a user has multiple categories:
1 fredflint shoes
2 fredflint pants
....
The second question I have is, why do you need a user table at all? It looks like all the information in the user table is already stored in the auction table! You can retrieve the user table simply by:
select distinct username, category
from auctions
If you need the separate table, an option to manually update the table when you create a new auction. I'd do it like this (I know just enough about triggers to avoid them):
1 - Make sure there's a row for this user
if not exists (select * from users where username = 'fredflint')
insert into users (username) values ('fredflint')
2 - Make sure he the shoe category
if not exists (select * from users where username = 'fredflint' and shoes = 1)
update users set shoes = 1 where username = 'fredflint'