SQL Query return unique result - mysql

I have a scenario as shown below:
The Project Manager(pm) or Delivery manager(dm) should be able to view records assigned to him.
The Sow and Child_Sow contains project_Id and User_id both primary keys.
The Project table contains project_id_sys which is not primary key.
The result I want is unique records for sow and child_sow which contains project_id_sys as some list of values.
Is it possible? Maybe the design of the tables is faulty or incomplete. Currently, the returned results shows many rows instead of basic rows who he/she is eligible.
Sow Table
sow_id
project_id (fk to project_id)
sow_desc
Child_Sow Table
child_sow_id
project_id (fk to project_id)
child_sow_desc
project table
project_id
project_id_sys
pm
dm
User Table
User_id
User_id_sys
My current query is:
select sow.project_id,child_sow.project_id,project.project_id
from project
inner join sow
on sow.project_id = project.project_id
join child_sow
on child_sow.project_id = project.project_id
where project.project_id_sys IN( 4001);

Related

how to Join only part of my first table to another table?

i have three tables:
account (which contain accounts Registered info and that Primary key is ads_id)
ads_info (which contain my advertising info and that Primary Key is ads_id)
favorite_ads (which that columns is fav_id, acc_id And ads_id) that specifies witch User Favorite which advertising.
Now i want to separate records which have acc_id = 1 from favorite_ads table and then outer-join this records with all of my ads_info table records.
can tell my any sql query do some thins like it for me?
You may try below query -
SELECT *
FROM ads_info AI
LEFT JOIN (SELECT fav_id, acc_id, ads_id
FROM favorite_ads
WHERE acc_id = 1) FA ON AI.ads_id = FA.ads_id

Data not being displayed when selecting two columns MySQL

I've created some tables in MySQL and I'm trying to select the data that's in those tables so that they get displayed. I have the following tables. Formed, Track, Album, Band, Customers and I have got the primary and foreign keys within the tables. I've also used the Insert into statement to insert data into the tables so there is data within the tables. I'm trying to get all the albums from a certain band to be displayed and I'm following the example below
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
Which can be found at W3Schools, to produce the following statement:
SELECT Album.AlbumID, Album.Title, Band.BandName
FROM Album
INNER JOIN Band
ON Album.BandID = Band.BandID
ORDER BY Band.BandName;
And this statement that I've made does create the table headers but doesn't display any data as shown here.
EDIT
In all the tables I've created, I hav got the primary key as an int AUTO_INCREMENT
EDIT #2
I've now changed it so that I have:
SELECT Album.AlbumID, Album.Title, Band.BandName
FROM Band
LEFT JOIN Album
ON Album.BandID = Band.BandID
ORDER BY Band.BandName;
Which displays only the band name and gets a NULL values for the AlbumID and Title
EDIT #3 Completed
I've managed to edit it so now I have the script working. It's as follows:
SELECT Album.AlbumID, Album.Title, Band.BandName
FROM Album
LEFT JOIN Band
ON Album.BandName = Band.BandName
ORDER BY Band.BandName;

MYSQL: Updating a customer field based on a partial match to another table's field

I have two tables:
customer, company
The customer table contains company_id and email_address while the company table contains company_id and URL
I'd like to run a query to update all the customer table's company_id to the matching company_id based on a partial match -- specifically if the customer's email_address contains the URL.
For example, if customer has customer#google.com it checks the company table to see if that email contains the URL google.com, and if so, it gives the customer the matching company_id from the company table.
What's an efficient way to do this in single query? Thanks!
I think this would do exactly what you want:
UPDATE customer
LEFT JOIN company
ON (customer.email LIKE CONCAT('%#', company.URL, '%'))
SET customer.company_id = company.company_id
WHERE company.company_id IS NOT NULL;
http://sqlfiddle.com/#!9/89765/1

MySQL query displaying more data than expected

I have MySql database connected to my Java app. My users can choose meals, category of meals, quantity, write note and order that meals. I store that orders in table usluga_hrana. At the moment I am working only with meals service but I have other services too, like drink service, wake up service and others. Thats why I need one more table for all orders from different services and its called narudzba. Now I need to display values of all these atributes in one query: broj_sobe (room number, table narudzba), id_narudzba (id order, table narudzba), naziv_kategorija (category name, table kategorija_jela), naziv_hrane (name of meal, table naziv_jela), kolicina (quantity, table usluga_hrana), napomena (note, table usluga_hrana), datum_vrijeme (date and time, table usluga_hrana) and izvrseno (done, table narudzba). Problem is that all these atributes are in different tables and when I execute my query, it displays me multiple values of orders, meals etc.
My tables are connected this way:
PK id_usluga (table usluga) is FK id_usluga in table narudzba
PK id_usluga (table usluga) is FK id_usluga in table usluga_hrana
PK id_kategorija (table kategorija_jela) is FK id_kategorija in table usluga_hrana
PK id_hrana (table naziv_jela) is FK id_hrana in table usluga_hrana
PK id_kategorija (table kategorija_jela) is FK id_kategorija in table naziv_jela
Here is album of my tables and result of my query with multiple values: http://imgur.com/a/6grPN
Here is album with rest of my tables: http://imgur.com/a/sFPie
Here is my query:
SELECT n.broj_soba, n.id_narudzba, kj.naziv_kategorija, nj.naziv_hrane, us.kolicina,
us.napomena, us.datum_vrijeme, n.izvrseno
FROM narudzba n
JOIN usluga u ON n.id_usluga = u.id_usluga
JOIN usluga_hrana us ON u.id_usluga = us.id_usluga
JOIN naziv_jela nj ON us.id_jela = nj.id_jela
JOIN kategorija_jela kj ON nj.id_kategorija = kj.id_kategorija
GROUP BY n.id_narudzba, us.id_usluga_hrana
I think my query is not good...
you name your table in not-English make us very hard to read/understand/think even though you already translate it to English :)
Your duplicate data can come from your query or your data table
I can see in your usluga_hrana table you have to records of Tomato soup (id=10) with different quantity (4 and 7). That make your query result 2 line of Tomato soup. Another example, You have 4 records of Greek Salad also but because 3 of them get the same quantity=1 so when query run, it return 2 row (quantity 1 and 2)
Not sure what you want, but if you do not want query result duplicate, you should not SELECT the quantity column and do DISTINCT the result if needed

Should I relate all of my MySQL tables to each other?

I'm working on a personal project for timekeeping on various projects, but I'm not sure of the best way to structure my database.
A simplified breakdown of the structure is as follows:
Each client can have multiple reports.
Each report can have multiple line items.
Each line item can have multiple time records.
There will ultimately be more relationships, but that's the basis of the application. As you can see, each item is related to the item beneath it in a one-to-many relationship.
My question is, should I relate each table to each "parent" table above it? Something like this:
clients
id
reports
id
client_id
line_items
id
report_id
client_id
time_records
id
report_id
line_item_id
client_id
And as it cascaded down, there would be more and more foreign keys added to each new table.
My initial reaction is that this is not the correct way to do it, but I would love to get some second(and third!) opinions.
The advantage of the way you're doing it is that you could check all time records for, say, a specific client id without needing a join. But really, it isn't necessary. All you need is to store a reference back up one "level" so to speak. Here are some examples from the "client" perspective:
To get a specific client's reports: (simple; same as current schema you suggest)
SELECT * FROM `reports`
WHERE `client_id` = ?;
To get a specific client's line items: (new schema; don't need "client_id" in table)
SELECT `line_items`.* FROM `line_items`
JOIN `reports` ON `reports`.`id` = `line_items`.`id`
JOIN `clients` ON `clients`.`id` = `reports`.`client_id`
WHERE `clients`.`id` = ?;
To get a specific client's time entries: (new schema; don't need "client_id" or "report_id" in table)
SELECT `time_records`.* FROM `time_records`
JOIN `line_items` ON `line_items`.`id` = `time_records`.`line_item_id`
JOIN `reports` ON `reports`.`id` = `line_items`.`id`
JOIN `clients` ON `clients`.`id` = `reports`.`client_id`
WHERE `client_id` = ?;
So, the revised schema would be:
clients
id
reports
id
client_id
line_items
id
report_id
time_records
id
line_item_id
EDIT:
Additionally, I would consider using views to simplify the queries (I assume you'll use them often), definitely creating indexes on the join columns, and utilizing foreign key references for normalization (InnoDB only).
No, if there is no direct relation in the elements of the model, then there should not be direct relation in the corresponding tables. Otherwise your data will have redundancies and you will have problems for updating.
This is the right way:
clients
id
reports
id
client_id
line_items
id
report_id
time_records
id
line_id
You don't need to create client_id on line_items table if you never join line items directly clients, becouse you can get that by reports table. Same happens to others FKs.
I recommend you think in your report needs/queries over this collection of data before create redundant foreign keys who can complicate your development.
Create redundant FKs is not difficult if you need them in the future, some ALTERS and UPDATE SELECTS solves your problem.
If you not have so much information in the line_items, you can denormalize and add this info in the time_records.
Anywhere there is a direct relationship between two tables, you should use foreign keys to keep the data integrity. Personally, I would look at a structure like this:
Client
ClientId
Report
ReportId
ClientId
LineItem
LineItemId
ReportId
TimeRecord
TimeRecordId
LineItemId
In this example, you do not need ClientId in LineItem because you have that relationship through the Report table. The major disadvantage of having ClientId in all of your tables is that if the business logic does not enforce consistency of these values (a bug is in the code) you can run into situations where you get different values if you search based on
Report:
ReportId = 3
ClientId = 2
LineItem:
LineItemId = 1
ReportId = 3
ClientId = 3
In the above situation, you would be looking at ClientId = 2 if your query went through Report and ClientId = 3 if your query went through LineItem It is difficult once this happens to determine which relationship is correct, and where the bug is.
Also, I would advocate for not having id columns, but instead more explicit names to describe what the id is used for. (ReportId or ClientId) In my opinion, this makes Joins easier to read. As an example:
SELECT COUNT(1) AS NumberOfLineItems
FROM Client AS c
INNER JOIN Report AS r ON c.ClientId = r.ClientId
INNER JOIN LineItem AS li ON r.ReportId = li.ReportId
WHERE c.ClientId = 12
As personal opinion, I would have:
clients
id
time_records
id
client_id
report
line_item
report_id
That way all of your fields are over in the time_records table. You can then do something like:
SELECT *
FROM 'time_records'
WHERE 'time_records'.'client_id' = 16542
AND 'time_records'.'report' = 164652
ORDER BY 'time_records'.'id' ASC