I have built a membership application that allows users to assemble projects whose contents are contained across 2 tables ('projects' and 'notes'). Each member can create, update or delete as many projects as they want.
Good so far...
I'd like the members to be able to share their projects with other members they choose. At this point I have built a function that allows Member A to type in an email address in order to share a project (with say, Member B). If that email exists in the DB it updates a third table 'sharing' with the project owner's ID (Member A), the "shared_with" member's ID (Member B) and the project ID. (Perhaps I have gone bullheaded in the wrong direction?)
The problem: How do I query the DB to show Member B all of their own projects + any projects that have been shared with them? The query below illustrates the direction I've been which has been useless. I am trying to say, "Select all from projects where user_id = (me) AND all corresponding projects where my ID is in the 'sharing' table under the 'shared_with' column. ...Oh yeah, and grab that project_id in order to know which project while you're at it."
My brain is mush. Any direction would be sincerely appreciated.
function find_all_projects($id) {
global $db;
$sql = "
SELECT *
FROM projects
LEFT
JOIN sharing
on projects.id = sharing.project_id
WHERE user_id = '" . db_escape($db, $id) . "'
OR sharing.shared_with = '" . db_escape($db, $id) . "'
ORDER
BY project_name
";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
Current Table Structure
From your question I believe your current table structure to be something like the following:
TABLE: user TABLE: project TABLE: shared
id | email | | id | user_id | content | | id | user_id | project_id
---+-------------------- ---+---------+------------------------------ ---+---------+------------
1 | james#website.com | | 1 | 1 | Project for James | | 9 | 1 | 5
2 | hannah#website.com | | 2 | 1 | Some other project for James | | 10 | 3 | 5
3 | lucy#website.com | | 3 | 2 | Project for Hannah | | 11 | 1 | 8
| | | 4 | 2 | A new project for hannah | | 12 | 2 | 8
| | | 5 | 2 | Hannah's pride and Joy | |
| | | 6 | 3 | Lucy cracking down | |
| | | 7 | 3 | Lucy's second project | |
| | | 8 | 3 | Lucy's public stuff | |
SQL
Example: https://www.db-fiddle.com/f/6KnEsGUmy5PS42usmzyTEX/0
SELECT project.id, project.user_id AS owner_id, shared.user_id AS shared_id, project.content
FROM project
LEFT JOIN shared
ON project.id = shared.project_id
AND project.user_id <> ?
WHERE project.user_id = ?
OR shared.user_id = ?;
N.B.
The key difference between this SQL statement and the one in your question is
AND project.user_id <> ?
Without that condition in the ON clause you will get duplicate records for every shared project for that user. I.e. if the user has shared the project with 20 users then there will be 20 duplicates.
This is expected behaviour as explained here: PHP while statement echoes duplicates
PHP
$sql = "
SELECT project.id, project.user_id AS owner_id, shared.user_id AS shared_id, project.content
FROM project
LEFT JOIN shared
ON project.id = shared.project_id
AND project.user_id <> ?
WHERE project.user_id = ?
OR shared.user_id = ?
";
$query = $mysqli->prepare($sql);
$query->bind_param("iii", $user_id, $user_id, $user_id);
$query->execute();
Alternate Table Structure
I suggest updating your table structure so that you have three tables (effectively: users, projects, and project_users). The project_user table then acts as a conduit between the two entities (users and projects). In this case storing the relationship between the two (i.e. owner vs shared with).
TABLE: user TABLE: project TABLE: project_user
id | email | | id | content | | id | user_id | project_id | role
---+-------------------- ---+------------------------------ ---+---------+------------+-----
1 | james#website.com | | 1 | Project for James | | 1 | 1 | 1 | 1
2 | hannah#website.com | | 2 | Some other project for James | | 2 | 1 | 2 | 1
3 | lucy#website.com | | 3 | Project for Hannah | | 3 | 2 | 3 | 1
| | | 4 | A new project for hannah | | 4 | 2 | 4 | 1
| | | 5 | Hannah's pride and Joy | | 5 | 2 | 5 | 1
| | | 6 | Lucy cracking down | | 6 | 3 | 6 | 1
| | | 7 | Lucy's second project | | 7 | 3 | 7 | 1
| | | 8 | Lucy's public stuff | | 8 | 3 | 8 | 1
| | | | | | 9 | 1 | 5 | 2
| | | | | | 10 | 3 | 5 | 2
| | | | | | 11 | 1 | 8 | 2
| | | | | | 12 | 2 | 8 | 2
SQL
Example: https://www.db-fiddle.com/f/imQZ6cvEEff4VgRQ4v22Qo/0
SELECT project.id, project_user.user_id, project_user.role, project.content
FROM project
JOIN project_user
ON project_user.project_id = project.id
WHERE project_user.user_id = ?;
PHP
$sql = "
SELECT project.id, project_user.user_id, project_user.role, project.content
FROM project
JOIN project_user
ON project_user.project_id = project.id
WHERE project_user.user_id = ?
";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $user_id);
$query->execute();
You can use another relationship between members and projects with a table like this :
CREATE TABLE `project_members` (
`project_id` INT NOT NULL,
`member_id` INT NOT NULL,
`is_owner` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`project_id`, `member_id`));
This table allows you to have many members linked to many projects.
The column is_owner is a boolean to easily see if the member is the owner or if the project has been shared to him.
Also it would be good to add foreign keys to project_id and member_id.
Related
I am working on a project to catalogue laptops and as such am trying to re-use as much information as possible. A simplified version of the MySQL tables are:
Table: laptop
|----------------------------------|
| id | make | line | model |
| 1 | 1 | 1 | Late 2015 13" |
|----------------------------------|
Table: make
|----------------------------------|
| id | name | other info |
| 1 | Apple | |
|----------------------------------|
Table: line
|----------------------------------|
| id | name | other info |
| 1 | MacBook Pro | |
|----------------------------------|
Table: networking
|----------------------------------|
| id | name | other info |
| 1 | A wifi card | |
| 2 | Another card | |
| 3 | Yet another | |
|----------------------------------|
Table: laptop_networking
|----------------------------------|
| id | networking | laptop |
| 1 | 3 | 1 |
| 2 | 1 | 1 |
|----------------------------------|
So far I used the current statement to retrieve the data in PHP
$statement = $dbc->prepare("
SELECT l.id
, m.id AS makeID
, m.name AS makeName
, n.id AS lineID
, n.name AS lineName
, l.model
FROM laptop l
JOIN make m
ON l.make = m.id
JOIN line n
ON l.line = n.id
WHERE l.id = :laptop);
$statement->bindParam(':laptop', $anID, PDO::PARAM_INT);
$statement->execute();
$theLaptop = $statement0>fetch();
At present running this code with $anID = 1 returns
|---------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | Model |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" |
|---------------------------------------------------------------|
What I would like to do is append another column to the table which returns all names from Networking which have an ID equal to a row in laptop_networking where the laptop field is equal to the ID from the retrieved laptop row
Such as:
|------------------------------------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | model | networking |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" | Yet another, A wifi card |
|------------------------------------------------------------------------------------------|
Is this possible as my many attempts at different types of JOINs have not yielded the desired results.
Thank you
Try this query:
SELECT laptop.id,
make.id AS makeID,
make.name AS makeName,
line.id AS lineID,
line.name AS lineName,
laptop.model,
t.networking
FROM laptop
INNER JOIN make
ON laptop.make = make.id
INNER JOIN line
ON laptop.line = line.id
INNER JOIN
(
SELECT t1.laptop, GROUP_CONCAT(t2.name) AS networking
FROM laptop_networking t1
INNER JOIN networking t2
ON t1.networking = t2.id
GROUP BY t1.laptop
) t
ON laptop.id = t.laptop
WHERE laptop.id = :laptop
Demo here:
Rextester
Here is the scenario. I have different levels of users. the user creation process is like this:
admin -> reseller -> marketer -> autoservice
I am trying to write a SQL query to select all autoservices created by a specific reseller. all users are saved in users table which has the following simplified structure:
+----+--------+--------------+-------------+-----------+
| id | userid | username | role | createdby |
+----+--------+--------------+-------------+-----------+
| 1 | 334455 | reseller1 | reseller | admin |
| 2 | 245578 | marketer1 | marketer | reseller1 |
| 3 | 235677 | autoservice1 | autoservice | marketer1 |
| 4 | 253569 | autoservice2 | autoservice | marketer1 |
| 5 | 234267 | autoservice3 | autoservice | marketer1 |
| 6 | 245468 | marketer2 | marketer | reseller1 |
| 5 | 434567 | autoservice4 | autoservice | marketer2 |
| 5 | 532263 | autoservice5 | autoservice | marketer2 |
| 5 | 634262 | autoservice6 | autoservice | marketer2 |
+----+--------+--------------+-------------+-----------+
The query should select autoservice1, autoservice2, autoservice3, autoservice4, autoservice5, autoservice6 and all their fields. currently I'm doing this with a combination of MySQL and php. First I select all marketers created by reseller1:
$sql="SELECT * FROM marketers WHERE createdby=:createdby";
$st=$conn->prepare($sql);
$st->bindvalue(":createdby",'reseller1',PDO::PARAM_STR);
$st->execute();
$usersArray=$st->fetchAll();
$NumberOfusers=$st->rowcount();
Then I loop through the results:
$MembersGeoData=array();
$MembersCount=0;
for($i=0;$i<$NumberOfusers;$i++) {
$sql="SELECT * FROM autoservices WHERE createdby=:createdby";
$st=$conn->prepare($sql);
$st->bindvalue(":createdby",$usersArray[$i]['username'],PDO::PARAM_STR);
$st->execute();
$tempUsersArray=$st->fetchAll();
$tempNumberOfusers=$st->rowcount();
$MembersGeoData=array_merge($MembersGeoData,$tempUsersArray);
$MembersCount+=$tempNumberOfusers;
}
This works but seems to be very inefficient. How can I do this with one sql query?
Assuming that your hierarchy is exactly correct (it is never skipped and a marketer never creates another marketer), then:
select sa.*
from autoservices sm join
autoservices sa
on sa.role = 'autoservice' and
sm.role = 'marketer' and
sm.username = sa.createdBy
where sm.createdBy = 'reseller1';
You are correct. You should let the database do this work.
I used The answer from #Gordon Linoff and answered my question :
SELECT a.* FROM autoservices AS a
JOIN marketers AS m
ON a.createdby=m.username
WHERE m.createdby='reseller1'
I have two table 'users' and 'friends' I am having difficulty joining them
users table
id | name | usercode
--------------------
1 | david | 2WM
2 | Samme | E5N
3 | Awudu | C0Q
4 | John | VX6
5 | Jerem | FG3
Friends Table
id | actor | target
--------------------
1 | E5N | FG3
2 | 2WM | VX6
3 | FG3 | 2WM
4 | C0Q | VX6
5 | FG3 | VX6
Basically i want to select all users from USERS table who has 'FG3' in either target or actor column in the FRIENDS table.
The result will be
id | name | usercode | actor | target
--------------------------------------
2 | Samme | E5N | E5N | FG3
1 | david | 2WM | FG3 | 2WM
5 | John | VX6 | FG3 | VX6
I have triend everything i know but still i am not getting the correct results
I will be glad if anyone can help me since I need to present this work tomorrow morning. Thank you
Looks like you want to join on usercode equals actor or target, then put the 'FG3' part in a WHERE clause:
SELECT users.id, users.name, users.usercode, friends.actor, friends.target
FROM users
INNER JOIN friends
ON users.usercode = friends.actor OR users.usercode = friends.target
WHERE users.usercode != 'FG3'
AND (friends.actor = 'FG3' OR friends.target = 'FG3');
Using INNER JOIN limits your query to only records that exist in both tables.
I have 2 tables, the 'department' and 'document'.
Table department
| doc_id | dept_name |
----------------------------------
| 1 | Information Technology|
| 2 | Software Development |
| 3 | Human Resource |
| 4 | Accounting |
| 5 | Support |
Table document
| doc_id | doc_name | author | description | department |
----------------------------------------------------------------------------
| 1 | Maps | User1 | sample | Information Technology |
| 2 | Audits | User3 | sample | Software Development |
| 3 | Image | User1 | sample | Information Technology |
| 4 | Papers | User4 | sample | Human Resource |
| 5 | Print Screen| User1 | sample | Software Development |
| 6 | Transaction | User3 | sample | Accounting |
| 7 | Graph | User1 | sample | Support |
| 8 | Excel | User1 | sample | Information Technology |
Now, I want to display the table with two columns: department and total_doc.
Output:
| department |total_doc|
-----------------------------------
| Information Technology| 3 |
| Software Development | 2 |
| Human Resource | 1 |
| Accounting | 1 |
| Support | 1 |
I want to display the total document inside the department and arrange them in ascending order.
Here's my query.(not sure)
SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name
I'm using MVC pattern in Codeigniter.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('doc_name');
Also, How can I display this in table? like using foreach in html?
You need to do group by with department not with doc_name.
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('department');
$result = $this->db->get()->result();
Hope This will help you.
foreach ($result as $row)
{
echo $row->department."----".$row->total_doc;
}
here you go
SELECT dept_name,COUNT(td.department) FROM department d
LEFT JOIN tdocument td ON td.`department`=d.`dept_name`
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC;
You want one line per department. IN SQL words: You want to group by department.
select department, count(*) as total_doc from document group by department;
(BTW: don't use single quotes for column aliases.)
I have three tables: years, employees, positions. Suppose that I already have these data in those tables.
years:
----------------
| id | name |
----------------
| 1 | 2011 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
---------------------------------------------------------
========================================
The years table is a central point.
If I insert a new year record, I must also copy all positions and employees which are related to the previous year.
So if I insert year 2012 into the years table, the data is suppose to be like this:
years:
----------------
| id | name |
----------------
| 1 | 2011 |
| 2 | 2012 |
----------------
positions:
------------------------------
| id | name | year_id |
------------------------------
| 1 | Director | 1 |
| 2 | Manager | 1 |
| 3 | Director | 2 |
| 4 | Manager | 2 |
------------------------------
employees:
---------------------------------------------------------
| id | name | position_id | year_id |
---------------------------------------------------------
| 1 | Employee A (Director) | 1 | 1 |
| 2 | Employee B (Manager) | 2 | 1 |
| 3 | Employee A (Director) | 3 (?) | 2 |
| 4 | Employee B (Manager) | 4 (?) | 2 |
---------------------------------------------------------
NOTICE the question marks in the third and fourth row of employees table.
I use these queries to insert a new year and copy all related positions and employees:
// Insert new year record
INSERT INTO years (name) VALUES (2012);
// Get last inserted year ID
$inserted_year_id = .......... // skipped
// Copy positions
INSERT INTO positions (name, year_id) SELECT name, $inserted_year_id AS last_year_id FROM positions WHERE year_id = 1;
// Copy employees
INSERT INTO employees (name, position_id, year_id) SELECT name, position_id, $inserted_year_id AS last_year_id FROM employees WHERE year_id = 1;
The problem is at copying employees query. I can't find a method to get or track the new ID of positions.
Is there a simple method to do this?
Thank you very much.
Your data model is seriously flawed and probably needs a complete overhaul, but if you insist on copying the data like you describe, this should do the trick:
// Copy employees
INSERT INTO employees (name, position_id, year_id)
SELECT name, new_positions.id, $inserted_year_id AS last_year_id
FROM employees
JOIN positions AS old_positions ON old_positions.id = employees.position_id
AND old_positions.year_id = employees.year_id
JOIN positions AS new_positions ON new_positions.name = old_positions.name
AND new_positions.year_id = $inserted_year_id
WHERE employees.year_id = 1
I think you should read about database normalization. Copying the data leads to maintenance issues and erroneous reporting.
If you went with a different design like the following, then there would be nothing to insert, until an employee changes position, is terminated, or a position is discontinued. There are plenty of other ways to approach this, too, but you should minimize redundancy (i.e. have only one copy of each Employee), and then keep track of data that changes over time, separately. Also read about foreign keys before you try to implement something like this.
positions:
-- If you are keeping track of the years that each position is active,
-- using dates provides simplicity. Note: this design assumes that positions
-- are never reactivated after being deactivated.
------------------------------------------------
| id | name | DateActive | DateInactive |
------------------------------------------------
| 1 | Director | 01/01/2011 | |
| 2 | Manager | 01/01/2011 | |
------------------------------------------------
employees:
---------------------------------------------------------------
| id | name | DateHired | DateTerminated |
---------------------------------------------------------------
| 1 | Employee A | 01/01/2011 | |
| 2 | Employee B | 01/01/2011 | |
| 3 | Employee C | 01/01/2011 | 10/01/2012 |
---------------------------------------------------------------
EmployeePositionRelationships
--If you are keeping track of time that each employee held a position
-- Employee A has been a Director since 1/1/2011
-- Employee B was a Manager from 1/1/2011 to 10/6/2012. Then they became a Director
-- Employee B was a Manager from 1/1/2011 to 10/1/2012. Then they were terminated
--------------------------------------------------------
EmployeeId | PositionId | DateStarted | DateEnded |
--------------------------------------------------------
1 | 1 | 01/01/2011 | |
2 | 2 | 01/01/2011 | 10/6/2012 |
3 | 2 | 01/01/2011 | 10/1/2012 |
2 | 1 | 10/6/2012 | |
--------------------------------------------------------