This question already has answers here:
SQL Join Differences
(5 answers)
Closed 7 years ago.
can please someone help me? I do the work at school and I dont know how connect these two tables.
I have two tables :
|Analyze | | Data
+-------------------------+ +-------------------------+
| id_analyze | Name | | id_analyze | Standard |
--------------------------- -------------------------
| 1 | One | 1 | A.11 |
| 2 | two | 1 | A.12 |
| 3 | tree | 1 | A.13 |
| 4 | four | 2 | A.21 |
| 5 | five | 2 | A.22 |
| id_analyze | Name | 3 | A.31 |
All, what I need is get output on web page from these two tables like:
| One | A.11 |
| | A.12 |
| | A.13 |
---------------
| Two | A.21 |
| | A.22 |
I tried a lots of listing but nothing work. For example:
$choose = mysql_query("select * FROM Analyze", $connection);
$choose2 = mysql_query("select * FROM Data,Analyze WHERE Data.id_analyze = Analyze.id_analyze", $connection);
while ($row = mysql_fetch_array( $choose ) ){
while ($row2 = mysql_fetch_array( $choose2 )) {
$Name = $row['Name'];
$Standard = $row2['Standard'];
}
}
Simple JOIN query:-
SELECT Analyze.Name, Data.Standard
FROM Analyze
INNER JOIN Data
ON Data.id_analyze = Analyze.id_analyze
ORDER BY Analyze.Name, Data.Standard
Note that you can do joins how you have done them but the newer way is explicitly using INNER JOIN / LEFT OUTER JOIN / etc.
You can then just loop around the results of this once
Related
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.
This question already has answers here:
How to join two tables mysql?
(4 answers)
Closed 2 years ago.
I have two tables that looks something like this (made as example):
Table sales:
| ID | date | displayname | status |
| 1 | 2020/08/03 16:25:26 | Angel | OK |
| 2 | 2020/08/03 16:25:26 | Angel | OK |
| 3 | 2020/08/03 16:25:26 | Cabil | X |
| 4 | 2020/08/03 16:25:26 | Syed | OK |
...
Table users (all of the columns has value, but removed for GDPR reasons):
| ID | displayname | fullname | email |
| 1 | Angel | | |
| 2 | Nico | | |
| 3 | Raquie | | |
| 4 | Cabil | | |
| 5 | Syed | | |
...
I have a PHP script that looks like this:
<?php
$query = "SELECT * FROM sales WHERE status='OK' ORDER BY STR_TO_DATE(`date`, '%Y/%m/%d %H:%i:%s') DESC LIMIT 5";
if ($result = $link->query($query)) {
$num_rows = 0;
while ($row = $result->fetch_assoc()) {
$num_rows++;
echo '<div class="my-box">';
echo "{$row['id']}";
echo "{$row['date']}";
echo "{$row['dbirth']}";
echo "{$row['email']}";
echo "{$row['displayname']}";
echo '</div>';
}
$result->free();
}
?>
Now it currently displays each displayname for each sale in echo "{$row['displayname']}";, but insted of the displayname, I want to show the fullname for the user that has the current display name. How can I accomplish this?
You seem to be looking for a join:
select s.*, u.fullname
from sales s
inner join users u on u.displayname = u.displayname
I have 1 master_table and 2 sub_tables. I want the join the 3 columns together (but the problem is the 2 sub_tables do not have any column that share the same value) and then SELECT * based on 2 different columns from the 2 sub_tables.
I've searched and tried many ways of coding, but couldn't find a solution.
SELECT *
FROM (master INNER JOIN sub_1 ON master.id=sub_1.id WHERE sub_1.column_1 = 'Y')
AND (master INNER JOIN sub_2 ON master.id=sub_2.id WHERE sub_2.column_2 = 'Y')
ORDER BY master.id
++++++++++++++++++++++++++++++++++++++++++++++++++
* Finally, solved. See the solution at the bottom of this post. *
++++++++++++++++++++++++++++++++++++++++++++++++++
===========
Edit: explain more about my data, problem and MySQL code
I have 3 tables stored in MySQL as follow
Master_table: regist
------------------------------------------
| reg_no | firstname | lastname | submit |
------------------------------------------
| 1 | first_A | last_A | N |
| 2 | first_B | last_B | A |
| 3 | first_C | last_C | P |
| 4 | first_D | last_D | P |
| 5 | first_E | last_E | A |
| 6 | first_F | last_F | N |
| 7 | first_G | last_G | N |
| 8 | first_H | last_H | A |
------------------------------------------
Sub_1: sub_A Sub_2: sub_P
------------------------------ ------------------------------
| reg_no | A_title | reply_A | | reg_no | P_title | reply_P |
------------------------------ ------------------------------
| 2 | 222 | Y | | 3 | 333 | N |
| 5 | 555 | N | | 4 | 444 | Y |
| 8 | 888 | Y | ------------------------------
------------------------------
I want to create a query that gives result like this
----------------------------------------------------------------------------------
| reg_no | firstname | lastname | submit | A_title | reply_A | P_title | reply_P |
----------------------------------------------------------------------------------
| 2 | first_B | last_B | A | 222 | Y | | |
| 8 | first_H | last_H | A | 888 | Y | | |
| 4 | first_D | last_D | P | | | 444 | Y |
----------------------------------------------------------------------------------
or
-----------------------------------------------------------
| reg_no | firstname | lastname | submit | title | reply |
-----------------------------------------------------------
| 2 | first_B | last_B | A | 222 | Y |
| 8 | first_H | last_H | A | 888 | Y |
| 4 | first_D | last_D | P | 444 | Y |
-----------------------------------------------------------
$sql = "SELECT *
FROM (regist INNER JOIN sub_A ON regist.reg_no = sub_A.reg_no WHERE sub_A.reply_A = 'Y')
AND (regist INNER JOIN sub_P ON regist.reg_no = sub_P.reg_no WHERE sub_P.reply_P = 'Y')
ORDER BY regist.reg_no";
Expected outcome:
ECHO personal data of all registrants who got reply as 'Y'
if($row['submit']=="A") $title = $row['A_title'];
elseif($row['submit']=="P") $title = $row['P_title'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['reg_no']." / ".$row['firstname']." ".$row['lastname']." / ".$title."<br>";
}
Problem: my SELECT code resulted in error. The code from #GMB and #Rogue didn't error, but echo give nothing.
If it is not possible to code a query as I want, I will just modify the column names (sub_1.reply_A and sub_2.reply_P) to be the same and change the input code in other webpages. However, it would be best if there is a way because I don't know whether the 'reply' columns were used somewhere else.
========================
Solution: a little modification from #Rogue code
SELECT *
FROM master
LEFT OUTER JOIN sub_1
ON master.id=sub_1.id
LEFT OUTER JOIN sub_2
ON master.id=sub_2.id
WHERE sub_1.column_1 = 'Y'
OR sub_2.column_2 = 'Y'
ORDER BY master.id
Do you just want simple JOINs between these 3 tables ?
SELECT m.*, s1.*, s2.*
FROM master m
INNER JOIN sub_1 s1 ON m.id=s1.id AND s1.column_1 = 'Y'
INNER JOIN sub_2 s2 ON m.id=s2.id AND s2.column_2 = 'Y'
ORDER BY m.id;
If you have master records that may not exist in both sub tables, you can switch to LEFT JOIN to avoid filtering them out.
Guidelines :
typical syntax is SELECT ... FROM table1 INNER JOIN table2 ON ... INNER JOIN table3 ON...
better put all conditions related to a JOINed table in the ON clause of the join rather than in the WHERE clause
avoid SELECT * : be specific about the columns you want to select
use table aliases to make the query easier to read
You're a little off syntactically:
SELECT *
FROM master
LEFT OUTER JOIN sub_1
ON master.id=sub_1.id
LEFT OUTER JOIN sub_2
ON master.id=sub_2.id
WHERE sub_1.column_1 = 'Y'
AND sub_2.column_2 = 'Y'
ORDER BY master.id
Personally I would recommend not using SELECT * and only grabbing the data you will need. As for determining what join to use, I like to link to CodingHorror's blog post in these times.
Edit: swapped INNER to LEFT OUTER, per OP's update
Hello I have two tables to send consecutive queries.
For example, table A yields 1,2,3 ..
Then, look for data in table B of query 1,2,3 ..
tableA
_____________________
| uid | rate |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
tableB
_________________________
| rate | text |
| 1 | ONE |
| 2 | TWO |
| 3 | THREE |
| 4 | FOUR |
===
<?php
$sql = $con->query("SELECT * FROM tableA WHERE uid=1");
$user = $sql->fetch_array();
$ratings = $user['rate']; //1,2,3
$sql2 = $con->query("SELECT * FROM tableB WHERE rate IN('".$ratings."')");
$text = $sql2->fetch_array();
$results = $text['text']; //ONE, TWO, THREE
?>
How best to do that?
You can use this query:
Select tableA.*,tableB.*
from tableA
join tableB on tableA.rate=tableB.rate
where tableA.uid=1
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'